JAVA(3ms) can be understanded easily.


  • 0

    public class Solution {
    public int myAtoi(String str) {

     	if(str==null || str.length()<=0) return 0;
    	int res=0;
    	int index=0; 
    	while((index<str.length())  &&  (str.charAt(index)==' ')){ 
                       index++;       //find the first non-whitespace
    	}
    	
    	int sign=0; //the count of signal.
    	boolean isNegative=false;   //the negative signal
    	for(;index<str.length() && (sign<2);index++){
    		char ch=str.charAt(index);
    		int val=ch-48;
    		if((ch=='+' || ch=='-')){
    			sign++;
    			if(ch=='-') isNegative=true;
    			continue;
    		}
    		if((val>9 || val<0))    //if there is other char , it it illegal.
    			break;
    		if(!isNegative && res>(Integer.MAX_VALUE-val)/10)
    			return Integer.MAX_VALUE;
    		
    		if(isNegative && ( res> (Integer.MAX_VALUE-val)/10))
    			return Integer.MIN_VALUE;
    		
    		res=10*res+val;  //the result of number
    	}
    	
    	if(isNegative)
    		return res*-1;
    	return res;
    }
    

    }


  • 0
    G

    this part of your code is wrong, it could raise out of boundary exception. for example, if input is all space which is invalid.

    while(str.charAt(index)==' '){ //find the first non-whitespace
    index++;
    }


  • 0
    This post is deleted!

  • 0

    @GoCodeZ thank you to point the mistake of my code.
    I have fix it . we could be add a sentence to judge the index is smaller than string's length.


  • 0
    K

    Good solution to handle overflow!

    Few nits: you could use str.trim() to remove white spaces. Also, str.isEmpty() is better for readability.


Log in to reply
 

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