Easy Java solution 4ms (easy to understand)


  • 1
    public class Solution {
        public int myAtoi(String str) {
            
             if(str == null || str.length() == 0)
                    return 0;
                    
             String mod = str.trim();//use trim to get rid of spaces at head and tail
             double ret = 0;//use double because test case will have huge number
             int i = 0;
             
             if(!(mod.charAt(0)=='+' || mod.charAt(0)=='-'|| ((mod.charAt(0) >= 48) && (mod.charAt(0) <= 57))))
             {
                  return 0;
             }   
             
             if(mod.charAt(0) == '+' || mod.charAt(0) == '-')
                        i++;
                        
             for(;i<mod.length();i++)
             {
                 {
                     if(((mod.charAt(i) >= 48) && (mod.charAt(i) <= 57)))
                     {
                         int current = mod.charAt(i)-48;//number
                         ret = ret*10+current;//add number
                     }
                     else
                        break;
                 }
             }
             
             
             if(mod.charAt(0) == '-')
                ret = ret*(-1);
            
            ret = ret >= Integer.MAX_VALUE ? Integer.MAX_VALUE:ret;
            ret = ret <= Integer.MIN_VALUE ? Integer.MIN_VALUE:ret;
            return (int)ret;
            
        }
    }
    
    

Log in to reply
 

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