My solution using JAVA


  • 1
    P

    one thing need to know is that you can not use a int type to judge if it is greater than 0x7fffffff, You have to use long type. and finally transfer it back to int.

     public class Solution {
            public int atoi(String str) {
                str=str.trim();
                long result = 0;
                int i = 0;
                boolean flag = false;
                if(str.equals(""))
                    return 0;
                if(str.charAt(0) == '-'){
                    flag = true;
                    i++;
                }
                if(str.charAt(0) == '+')
                    i++;
                for(; i < str.length(); i++){
                    if(str.charAt(i) > '9' || str.charAt(i) < '0')
                        break;
                    int a = (int)(str.charAt(i) - '0');
                    result = result*10 + a;
                    if(result > 0x7fffffff){
                        if(flag)
                            return 0x7fffffff * -1 - 1;
                        else
                            return 0x7fffffff;
                    }
                }
                if(flag)
                    return (int)result * -1;
                else
                    return (int)result;
            }
        }

Log in to reply
 

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