JAVA 5ms solution


  • 3
    F
    public class Solution {
        public int myAtoi(String str) {
            int p = 0, ret = 0;
            while(p <str.length() && Character.isWhitespace(str.charAt(p))) ++p;
            if(p == str.length()) return 0;
            boolean negFlag = (str.charAt(p) == '-');
            if(str.charAt(p) == '+'  || str.charAt(p) == '-') ++p;
            for(; p<str.length(); ++p) {
                if(str.charAt(p) > '9' || str.charAt(p) < '0') {
                    break;
                }else {
                    int digit = str.charAt(p) - '0';
                    if(!negFlag && ret > (Integer.MAX_VALUE - digit) /10) return Integer.MAX_VALUE;
                    else if(negFlag && ret < (Integer.MIN_VALUE + digit)/10) return Integer.MIN_VALUE;
                    ret = ret * 10 + (negFlag? -digit: digit);
                }
            }
            return ret;
            
        }
    }

  • 0
    S

    try input "2 3"


Log in to reply
 

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