[LeetCode][Java] String to Integer (atoi)

최지수·2021년 9월 30일
0

Algorithm

목록 보기
13/77
post-thumbnail

전 문제에 이어서 바로 풀었어요. 이전 문제의 연장선이란 느낌이 드네요.

문제

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).

The algorithm for myAtoi(string s) is as follows:

  1. Read in and ignore any leading whitespace.
  2. Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
  3. Read in next the characters until the next non-digit charcter or the end of the input is reached. The rest of the string is ignored.
  4. Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
  5. If the integer is out of the 32-bit signed integer range [231-2^{31}, 23112^{31} - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 23112^{31} - 1 should be clamped to 23112^{31} - 1.
    Return the integer as the final result.

제한사항

  • Only the space character ' ' is considered a whitespace character.
  • Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.

접근

atoi 알고리즘을 제대로 알고 계신 분이라면 쉽게 푸시겠지만 저는 그렇지 않아서요 ㅎㅎ ㅠ. 그러다보니 예외 처리를 신경쓰는데 시간을 잡았습니다.

조건 사항
1. 숫자가 구성되기 까지 공백은 무시
2. 이후 +-를 통해 양/음수를 판단(숫자가 나온 이후는 다~ 무시)
3. 숫자 구성 이후 모든 문자는 다 무시
4. 구성된 숫자가 Integer 범위를 넘어설 경우 내부 값으로 Clamp 처리

무시해야할 사항을 예외 처리하지 않다 보니 Test Case 보면서 풀었던 것 같습니다... 아직 독해력 늘리는데 노력이 필요할거 같아요.

답안

class Solution {
    public int myAtoi(String s) {
        long answer = 0;
        boolean isPositive = true, fixed = false;
        for(int nIndex = 0; nIndex < s.length(); ++nIndex) {
            char chr = s.charAt(nIndex);
            if(chr == ' '){
                if(fixed)
                    break;
                continue;
            }
            if(chr == '+'){
                if(fixed)
                    break;
                fixed = true;
            }
            else if(chr == '-'){
                if(fixed)
                    break;
                isPositive = false;
                fixed = true;
            }
            else if('0' <= chr && chr <= '9'){
                fixed = true;
                answer = (answer * 10) + (chr - '0');
                if(answer > Integer.MAX_VALUE){
                    return (isPositive) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                }
            }
            else{
                break;
            }
        }
        if(!isPositive)
            answer *= -1L;
        return (int)answer;
    }
}
profile
#행복 #도전 #지속성

0개의 댓글