8. String to Integer (atoi)

JJ·2021년 2월 1일
0

Algorithms

목록 보기
90/114
class Solution {
    public int myAtoi(String str) {
        String r = "";
        Set<Character> s = new HashSet<Character>();
        s.add('1');
        s.add('2');
        s.add('3');
        s.add('4');
        s.add('5');
        s.add('6');
        s.add('7');
        s.add('8');
        s.add('9');
        
        boolean start = false; 
        boolean isPos = true;
        for (int i = 0; i < str.length(); i++) {
            if (s.contains(str.charAt(i))) {
                start = true; 
                r += str.charAt(i);
            } else if (start && str.charAt(i) == '0') {
                r += "0";
            } else if (str.charAt(i) == '-') {
                isPos = false; 
            }
        }
        
        int result = Integer.parseInt(r);
        
        if (! isPos) {
            result = result * -1;
        }
        
        return result; 
    }
}

3 / 1082 test cases passed.

ATOI의 뜻을 잘 이해 못했었음...^^

class Solution {
    public int myAtoi(String str) {
        int i = 0;
        int sign = 1;
        int result = 0;
        if (str.length() == 0) return 0;

        //Discard whitespaces in the beginning
        while (i < str.length() && str.charAt(i) == ' ')
            i++;

        // Check if optional sign if it exists
        if (i < str.length() && (str.charAt(i) == '+' || str.charAt(i) == '-'))
            sign = (str.charAt(i++) == '-') ? -1 : 1;

        // Build the result and check for overflow/underflow condition
        while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
            if (result > Integer.MAX_VALUE / 10 ||
                    (result == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > Integer.MAX_VALUE % 10)) {
                return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            result = result * 10 + (str.charAt(i++) - '0');
        }
        return result * sign;

    }
}

Runtime: 1 ms, faster than 100.00% of Java online submissions for String to Integer (atoi).
Memory Usage: 39.4 MB, less than 25.04% of Java online submissions for String to Integer (atoi).

0개의 댓글