Simple 330ms Java solution


  • 0
    X
    public class Solution {
    public int myAtoi(String str) {
        if(str==null)
            return 0;
        boolean isPositive=true;
        boolean isSignal =false;
        boolean isBlank = false;
        char  []s = str.toCharArray();
        int length = str.length();
        long rst=0L;
        long tmp=(long)2147483648L;
        for(int i=0;i<length;i++){
            if(s[i]!=' '){// take ' 'into consideration
                isBlank=true;
                if(isSignal==false&&s[i]=='-'){ //take the '+''-'into consideration,only once
                    isPositive =false;
                    isSignal =true;
                  }
                else if(isSignal==false&&s[i]=='+'){
                    isPositive =true;
                    isSignal =true;
                 }
                else{
                    if(s[i]>='0'&&s[i]<='9'){ //only number allowed
                        rst = rst*10+s[i]-'0';
                        if(rst>=tmp&& isPositive==true){ // if too large
                            return 2147483647;
                        }
                        if(rst>=tmp&& isPositive ==false){//if too small
                            return -2147483648;
                        }
                     }
                    else {
                        break;
                    }
                }
            }else{
                if(isBlank==true){//if the ' 'exits among the numbers
                    return (int)rst;
                }
            }
        }
        
        if(isPositive){
            return (int)rst;
        }else{
            return -(int)rst;
        }
    }
    

    }


Log in to reply
 

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