Super fast Java solution


  • 0
    public int myAtoi(String str) {
            long res = 0;
            boolean neg = false;
            String s = str.trim();
            for(int i=0; i<s.length(); i++){
                char c = s.charAt(i);
                if((c=='-' || c == '+') && i==0) neg = c=='-'; 
                else if(c>='0' && c<='9') res = res*10 + c-'0';
                else break;
                if(i>8 && !neg && res>Integer.MAX_VALUE) return Integer.MAX_VALUE;
                if(i>8 && neg && -1*res<Integer.MIN_VALUE) return Integer.MIN_VALUE;
            }
            return (int)(neg?-1*res:res);
        }
    

Log in to reply
 

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