[JAVA] Solution using char arrays and Number Format Exception


  • 0
    V

    Code using some hacks with numbers.

    public int reverse(int x) {
            int sign = 1;
            if(x < 0) {
              sign = -1; 
              x = x * sign;
            }
            
            char[] intChar = ("" + x).toCharArray();
            for(int i=0; i<intChar.length/2; i++) {
                char temp = intChar[i];
                intChar[i] = intChar[intChar.length-i-1];
                intChar[intChar.length-i-1] = temp;
            }
            try {
                return Integer.parseInt(new String(intChar)) * sign;
            } catch(NumberFormatException e) {
                return 0;
            }
        }
    

Log in to reply
 

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