June 08, 2022

8. String to Integer (atoi)

8. String to Integer (atoi)

class Solution {
    public int myAtoi(String str) {
        long res = 0;
        char sign = 0;
        boolean hasRes = false;
        
        int i = 0;
        while (i < str.length()) {
            char c = str.charAt(i);
            if (c == ' ') {
                if (hasRes) {
                    break;
                }
                i++;
            } else if (c == '+' || c == '-') {
                if (hasRes) {
                    break;
                }
                if (sign != 0) {
                    return 0;
                }
                hasRes = true;
                sign = c;
                i++;
            } else if (!Character.isDigit(c)) {
                if (hasRes) {
                    break;
                }
                return 0;
            } else {
                int digit = Character.getNumericValue(c);
                res = res * 10 + digit;
                hasRes = true;
                if (res > Integer.MAX_VALUE) {
                    if (sign == '-') {
                        return Integer.MIN_VALUE;
                    } else {
                        return Integer.MAX_VALUE;
                    }
                }
                i++;
            }
        }
        
        if (sign == '-') {
            res = res * (-1);
        }
        return (int) res;
        
    }
}
comments powered by Disqus