My Java Solution


  • 0
    R
    public class Solution {
        public int myAtoi(String str) {
            str = str.trim(); // Trim white spaces, if any
            boolean signFlag = false; // String shall contain only one sign character
            int isNegative = 1; // 1 for positive numbers, -1 for negative numbers
            int number = 0; //Value to be returned
            
            for (int i=0; i < str.length(); i++) {
                char currentChar = str.charAt(i);
                
                if (currentChar == '+' || currentChar == '-') {
                    // A number must have only 1 sign
                    if (signFlag == false) { 
                        signFlag = true;
                        isNegative = currentChar == '-' ? -1 : 1;
                    } else break; // If input string has more than 1 sign characters 
                }
                else if(currentChar > '9' || currentChar < '0') { // If current character is not a digit
                    break;
                } else {
                    // currentChar is a digit convert it to int and make sure it doesn't cross the range of Integer
                    int currentInt = (int) currentChar - 48;
                    if (number > (Integer.MAX_VALUE - currentInt)/10) return Integer.MAX_VALUE;
                    if (number < (Integer.MIN_VALUE + currentInt)/10) return Integer.MIN_VALUE;
                    number = number*10 + isNegative*(currentInt);
                }
                
            }
            return number;
        }
    }
    

Log in to reply
 

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