Why Runtime error?


  • 0
    L

    I always get the following error message:

    Runtime Error Message: Line 32: java.lang.NumberFormatException: For input string: "2147483648"

    Last executed input: "-2147483648"

    My code:

    public class Solution {
           public int atoi(String str) {
                //null or ""
                if(str==null||str.equals(""))
                    return 0;
                str=str.trim();
                boolean minus=false;
    
                if(str.charAt(0)=='-'){
                    minus=true;
                    str=str.substring(1);
                }
                if(!(str.charAt(0)>='0'&&str.charAt(0)<='9'))return 0;
                for(int i=1;i<str.length();i++)
                    if(!(str.charAt(i)>='0'&&str.charAt(i)<='9'))
                        str=str.substring(0,i);
                if(!minus){
                    if(str.length()>10)return Integer.MAX_VALUE;
                    else if(str.length()==10&&str.compareTo("2147483647")>0)
                        return Integer.MAX_VALUE;
                }else{
                    if(str.length()>10)return Integer.MIN_VALUE;
                    else if(str.length()==10&&str.compareTo("2147483648")>0)
                        return Integer.MIN_VALUE;
                }
    
                //"0123"
                int num=Integer.parseInt(str);
                if(minus)num=-num;
                return num;
            }
        }

Log in to reply
 

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