Java solution - comments inline


  • 0
    G
    public int myAtoi(String str) {
            // Handle empty string and only whitespace case
            if (str.trim().isEmpty())
                return 0;
    
            // Used to handle sign
            int sign = 1;
            // Used to store number
            long num = 0;
    
            // Remove whitespaces
            str = str.trim();
    
            // Check for appropriate sign at the first non-whitespace character
            if (str.charAt(0) == '+' || str.charAt(0) == '-') {
                if (str.charAt(0) == '-')
                    sign = -1;
                str = str.substring(1);
            }
    
            // Loop through the non-whitespace characters
            for (int i=0;i<str.length();i++) {
                // Get integer value of character by subtracting its ASCII value with ASCII value of 0
                int val = str.charAt(i)-'0';
                // If it is a non-numeric character, it is either invalid char or reached end of numeric list
                if (val <0 || val>9)
                    break;
                num = num*10 + val;
                // Can break if value exceeds max integral value
                if (num > Integer.MAX_VALUE) {
                    break;
                }
            }
            
            // Return appropriate value based on sign
            if (num > Integer.MAX_VALUE) {
                if (sign == 1)
                    return Integer.MAX_VALUE;
                else
                    return Integer.MIN_VALUE;
            }
            return sign*((int)num);
    
        }
    

Log in to reply
 

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