Java solution

  • 0
    public int myAtoi(final String a) {
        int x=0;
        while(x<a.length()&&a.charAt(x)==' ') x++;
        String s = a.substring(x);
        if(s.length()==0) return 0;
        char sign = s.charAt(0)=='-'?'-':'+';
        long num = 0l;
        for(int i=0;i<s.length();i++){
            char c = s.charAt(i);
            if(i==0&&(c=='+'||c=='-')) continue;
            if(c<'0'||c>'9') break;
            num = num*10 + c-'0';
            if(sign=='+'&&num>Integer.MAX_VALUE) return Integer.MAX_VALUE;
            if(sign=='-'&&num*-1<Integer.MIN_VALUE) return Integer.MIN_VALUE;
        if(sign=='-') num = -1 * num;
        return (int)num;

Log in to reply

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