# Return reversed integer - Java [closed]

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.

• Hi, codereview is for refactoring working code to even better code. Stack Overflow can help you with bugs. Therefor, you should ask your question on codereview. Jul 4 '20 at 12:58

In Java and many others, int is a 32-bit data type which means it has the range $[-2^31, 2^31– 1]$. For the input "1534236569" which is reversed to "9646324351" is outside this range. As stated in the note, consider returning 0 when this occurs.