Java solution used a long value to avoid overflow


  • 0
    Y
    public class Solution {
        public int myAtoi(String str) {
            if(str == null || str.length() == 0) {
                return 0;
            }
            int i = 0;
            while(str.charAt(i) == ' ') {
                i++;
            }
            boolean negative = false;
            if(str.charAt(i) == '-') {
                negative = true;
                i++;
            } else if(str.charAt(i) == '+') {
                i++;
            }
            long res = 0;
            while(i < str.length() && Character.isDigit(str.charAt(i))) {
                res = res * 10 + (str.charAt(i) - '0');
                if(negative && -res < Integer.MIN_VALUE) {
                    return Integer.MIN_VALUE;
                } else if (!negative && res > Integer.MAX_VALUE) {
                    return Integer.MAX_VALUE;
                }
                i++;
            }
            if(negative) {
                res = -res;
            }
            return (int)res;
        }
    }

Log in to reply
 

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