My java solution


  • 0
    N
    public class Solution {
    public int myAtoi(String str) {
        
        
        double ans = 0 ;
        boolean isNeg = false ;
        boolean toNumChar = false;
        char strChar[] = str.toCharArray();
        int len = strChar.length;
        
        
        for(int i=0 ; i<len ; i++){
            
            if(strChar[i] ==' ' && toNumChar ==false) //pass the whitespace
                ; //do nothing
            else if( (strChar[i] =='-' || strChar[i] =='+') && toNumChar ==false){
                
                toNumChar = true;
                isNeg = ((strChar[i] =='-') ? true : false ) ;
                
            }else if(strChar[i]>=48 && strChar[i]<=57){
                toNumChar = true;
                int num = (int)strChar[i] - 48 ;
                ans = ans*10 + num ;
            }else if(toNumChar && (strChar[i]<48 || strChar[i]>57) ) 
                break;
            else
                return 0;
        }
        
        ans =  isNeg ? -ans : ans ; 
        
        if (ans >= Integer.MAX_VALUE)
            return Integer.MAX_VALUE ;
            
        if(ans <= Integer.MIN_VALUE)
            return Integer.MIN_VALUE ;
            
        return (int)ans ;
        
    }
    

    }


  • 0
    N

    Will it work in case of "-kkk-00111234asdf"?


Log in to reply
 

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