Simpe Java solution with Explanation


  • 0

    We will start to add up the characters when

    • we have passed all the leading whitespace
    • '+' or '-' comes up the first time
    • A non-numerical character comes up

    So I use a start signal(boolean start) to check the starting state.Once we starts, all non-numerical characters are invalid.

    As for the overflow problem,just turn if(res*10+tail>INT_MAX) to if(res>(INT_MAX-tail)/10)

    public class Solution {
        public int myAtoi(String str) {
            int res=0,p=1;
            boolean start=false;
            for(char c:str.toCharArray()){
               if(c==' ' && !start)continue;//pass the leading whitespace
               if((c=='+' ||c=='-')&&!start){
                   p=(c=='-')?-1:1;
                   start=true;
                   continue;
               }
                start=true;
                if(c-'0'<0 || c-'0'>9)return res*p;
                if(res>(Integer.MAX_VALUE-(c-'0'))/10)
                    return p==1?Integer.MAX_VALUE:Integer.MIN_VALUE;
                res=res*10+c-'0';
            }
            return res*p;
        }
    }

Log in to reply
 

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