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=='-')){
    			if(ch=='-') isNegative=true;
    		if((val>9 || val<0))    //if there is other char , it it illegal.
    		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
    		return res*-1;
    	return res;


  • 0

    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

  • 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

    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.