my simple JAVA solution with long type


  • 0

    Just use 'long' type and detect the negative, positive and pre-process space first.
    But I am confused the test case ' -012a42' its answer is -21. It is weird.

    public int myAtoi(String str) {
            if(str.length() == 0) return 0;
            int i = 0;
            while(i < str.length() && str.charAt(i) == ' ') i++;
            boolean neg = false;
            if(str.charAt(i) == '-') { neg = true; i++; }
            else if (str.charAt(i) == '+') i++;
            long total = 0;
            for(int k = i; k < str.length(); k++){
                if(str.charAt(k) < '0' || str.charAt(k) > '9') break;;
                total = total * 10 + (str.charAt(k) - '0');
                if(total >= Integer.MAX_VALUE && !neg) return Integer.MAX_VALUE;
                if(total > Integer.MAX_VALUE && neg) return Integer.MIN_VALUE;
            }
            return neg == false? (int) total : -1 * (int)total;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.