Java Version


  • 0
    I

    class Solution {
    public static boolean isValid;
    public int myAtoi(String str) {
    int ans = 0,c=0,i=0;
    int N = str.length();
    int k = 0;
    int INT_MAX = 2147483647 ,INT_MIN = -2147483648;
    StringBuilder s = new StringBuilder();

        boolean isNeg = false;
        if(N==0) return 0;
        
        // str pre-processing
        // "   +0 123"  --> 0
        // "  -0012a42" --> -0012
        // " b11228552307"
        for(int j=0;j<str.length();j++){
            if((str.charAt(j)!=' ')) {
                if(str.charAt(j)=='+'||str.charAt(j)=='-'||(str.charAt(j)-'0'<=9 && str.charAt(j)-'0'>=0)){
                    s.append(str.charAt(j));                    
                }else{
                    break;
                }
                k=j;
                if(++k<str.length() && (str.charAt(k)-'0'>9 || str.charAt(k)-'0'<0)) break;
            }
        }
    
        String str2 = new String(s);
        System.out.println(str2);
        int str2Len = str2.length();
        if(str2Len==0) return 0;
        if(str2Len>0 && str2.charAt(0)=='-'){
            isNeg = true;
            i++;
        }else if(str2Len>0 && str2.charAt(0)=='+'){
            //isNeg = false;
            i++;
        }
        
        while(i<str2Len && (str2.charAt(i)-'0'>9 || str2.charAt(i)-'0'<0)) i++; 
    
        if(i>1) {// too many '-' or '+'  "+-2" -->0
            isValid=true;
            return 0;
        }
        
        for(; i<str2Len; i++){
            c = str2.charAt(i)-'0';
            System.out.println("c="+c+"  i="+i);
            // "-2147483647" Expected: -2147483647
            // "2147483648"  Expected: 2147483647
            if(ans > INT_MAX / 10 || (ans == INT_MAX / 10 && c > INT_MAX%10)){ //int overflow ,return max
                System.out.println("overflow c="+c+"i="+i);
                isValid=true;
                System.out.println(isNeg);
                return isNeg?INT_MIN:INT_MAX;
            }    
            ans = ans*10+c;          
        }
    
        return isNeg?-ans:ans;
    }
    

    }


Log in to reply
 

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