I cannot understand why I have a java NumberFormatException


  • 0
    C
    public class Solution {
    public int reverse(int x) {
        int reversed;
        
        if (x < 10 && x > -10)
            return -x;
            
        String str = Integer.toString(x);    
        char revStr[] = new char[str.length()];
    
        if (str.charAt(0) == '-')
            str = str.substring(1);
    
        for(int i = 0; i < str.length()/2; i++)
        {
            char temp = str.charAt(i);
            revStr[str.length() - i - 1] = temp;
            revStr[i] = str.charAt(str.length() - i - 1);
        }
        
        if (str.length() % 2 == 1)
            revStr[str.length()/2] = str.charAt(str.length()/2);
            
        String s = String.valueOf(revStr);
        reversed = Integer.parseInt(s);
        
        if (x < 0)
            reversed *= -1;
    
        return reversed;
    }
    }
    

    I get the following error with input -123:

    Line 25: java.lang.NumberFormatException: For input string: "321"


Log in to reply
 

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