Simple Java solution


  • 0
    A
    public class Solution 
    {
        public int myAtoi(String str) 
        {
            str = str.trim();
            if(str.length()==0) return 0;
    
            int i = 0;
            int prev = 0;
            int num = 0;
    
            if(str.charAt(0) == '-') i = 1;
            if(str.charAt(0) == '+') i = 1;
    
            // System.out.println(str.charAt(0));
    
            while(i < str.length())
            {
                if(!Character.isDigit(str.charAt(i))) break;
                int curr = str.charAt(i) - '0';
                num = (prev * 10) + curr;
                if((str.charAt(0) != '-' && num < 0) || (str.charAt(0) != '-' && prev != num/10)) 
                {
                    return Integer.MAX_VALUE;
                }
                if((str.charAt(0) == '-' && num < 0) || (str.charAt(0) == '-' && prev != num/10)) 
                {
                    return Integer.MIN_VALUE;
                }
                prev = num;
                i++;
            }
    
            if(str.charAt(0) == '-') return -1*num;
            return num;
        }
    }
    

Log in to reply
 

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