Java Solution 3ms (easy to understand)


  • 1
    S

    """
    public class Solution
    {

    public int myAtoi(String str)
    {
        int result = 0;
        boolean isNegative = false;
        char[] array = str.toCharArray();
        int index = 0;
        
        if(array.length == 0)
        {
            return 0;
        }
        
        while(index < array.length)         //skip whitespace
        {
            if(array[index] != ' ')
            {
                break;
            }
            index++;
        }
        
        if(array[index] == '+' || array[index] == '-')      //handle sign + and - 
        {
            if(array[index] == '-')
            {
                isNegative = true;
            }
            index++;
        }
        
        for(int i = index ; i < array.length ; i++)
        {
            if(array[i] >= '0' && array[i] <= '9')
            {
                int addValue = array[i] - '0';
                
                if(result > Integer.MAX_VALUE / 10)         //overflow
                {
                    if(isNegative)
                        return Integer.MIN_VALUE;
                    else
                        return Integer.MAX_VALUE;
                }
                else if (result == Integer.MAX_VALUE / 10)      
                {
                    if(isNegative)
                    {
                       // treat it as postive number, -MIN_VALUE =  MAX_VALUE + 1
                        if(addValue >= (Integer.MAX_VALUE - result * 10 + 1))                              
                        {                                                
                            return Integer.MIN_VALUE;                   
                        }
                    }
                    else
                    {
                        if(addValue >= (Integer.MAX_VALUE - result * 10 ))
                        {
                            return Integer.MAX_VALUE;
                        }
                    }
                }
                
                result = result * 10 + addValue;
            }
            else
            {
                break;
            }
        }
        
        if(isNegative)
        {
            result = -result;
        }
        
        return result;
    }
    

    }

    """


Log in to reply
 

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