i think my solution is correct, see below:


  • 0
    L
    public class Solution {//未考虑int越界情况。
        public int myAtoi(String str) {
            if(str==null||str.length()==0){
                return 0;//i think here should throw a exception.
            }
            
            char first;
            
            if((first=str.charAt(0))=='+'||(first=str.charAt(0))=='-'){
                str=str.substring(1);
                if(str==null||str.length()==0){
                 return 0;//i think here should throw a exception.
            }
            }
            
            
            int len=str.length();
            int step=1;
            int res=0;
            for(int i=len-1;i>=0;i--){
                int offset=str.charAt(i)-'0';
                if(offset<0||offset>9){
                      return 0;//i think here should throw a exception.
                }
                res+=offset*step;
                step*=10;
                
            }
            return first=='-'?0-res:res;
        }
    }
    

Log in to reply
 

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