본문 바로가기
Algorithm/Leetcode

8. String to Integer (atoi) - 커스텀 atoi 구현(ascii to int) - c++

by Ellery 2020. 11. 23.

특정 조건을 만족하는 atoi를 직접 구현하는 문제이다

  • Only the space character ' ' is considered a whitespace character.
  • Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, 231 − 1 or −231 is returned.

string으로 들어오는 input에서 캐릭터값을 제거하고 부호와 숫자만 남기고 출력한다.

단 32bit int의 범위를 벗어나면 INT_MAX, INT_MIN을 반환한다. 그리고 숫자가 먼저 나오지 않는 string은 0을 반환한다

leetcode.com/problems/string-to-integer-atoi/

 

String to Integer (atoi) - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

/*
ref: 
http://cboard.cprogramming.com/linux-programming/125356-complete-function-definition-i-e-atoi.html
*/
#include <ctype.h>  // C++ 에서는 <cctype>

int atoi(char s[]) {
  int i, n, sign;
  for (i = 0; isspace(s[i]); i++)
    ; /* skip white space */
  sign = (s[i] == '-') ? -1 : 1;
  if (s[i] == '+' || s[i] == '-') /* skip sign */
    i++;
  for (n = 0; isdigit(s[i]); i++) n = 10 * n + (s[i] - '0');
  return sign * n;
}

atoi 구현예제를 참고해서 이를 수정하였다. <cctype> 라이브러리를 이용하면 whitespace와 숫자 관련 조건절을 쉽게 짤 수 있다. 

#include <cctype>   // isspace(), isdigit()
#include <climits>  // INT_MAX, INT_MIN
#include <iostream>
using namespace std;

class Solution {
   public:
    int myAtoi(string s) {
        int i = 0, sign = 1, n = 0;
        if (s.length() == 0) {
            return 0;
        }
        while (isspace(s[i])) {
            ++i;
        }
        sign = (s[i] == '-') ? -1 : 1;
        if (s[i] == '+' || s[i] == '-') {
            i++;
        }
        while (isdigit(s[i])) {
            if (n > INT_MAX / 10 || (n == INT_MAX / 10 && s[i] - '0' > 7)) {
                return sign == 1 ? INT_MAX : INT_MIN;
            }
            n = n * 10 + (s[i++] - '0');
        }
        return sign * n;
    }
};

32bit int 범위는 -2,147,483,648 to 2,147,483,647

읽어온 string 내의 숫자가 2_147_483_647 보다 크거나 같을 경우를 캐치하기 위해서

1의자리를 제외한 값과 1의 자리를 따로 검사하는 식을 짰다. 

'Algorithm > Leetcode' 카테고리의 다른 글

48. rotate image C++ 풀이  (0) 2020.11.17
26. Remove Duplicates from Sorted Array - C++ 풀이  (0) 2020.11.09