The question is from Leetcode.
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
My solution:
class Solution {
public int reverseInteger(int num) {
if(num >= 0) { // positive numbers
char[] arr = String.valueOf(num).toCharArray();
reverse(arr);
return Integer.parseInt(new String(arr));
} else { // negative numbers
num *= -1;
char[] arr = String.valueOf(num).toCharArray();
reverse(arr);
return -Integer.parseInt(new String(arr));
}
}
void reverse(char[] arr) {
int start = 0;
int end = arr.length - 1;
while (start < end) {
char temp = arr[start];
arr[start++] = arr[end];
arr[end--] = temp;
}
}
}
For one of the test cases, I am getting the following error:
java.lang.NumberFormatException: For input string: "9646324351"
at line 68, java.base/java.lang.NumberFormatException.forInputString
at line 658, java.base/java.lang.Integer.parseInt
at line 776, java.base/java.lang.Integer.parseInt
at line 6, Solution.reverse
at line 54, __DriverSolution__.__helper__
at line 84, __Driver__.main
I do not understand why the test case is failing? Any indications to resolve the exception or to improve the solution would be welcome. Thank you.