Reverse digits of an integer.
Example1:
x = 123,
return 321 Example2:
x = -123,
return -321
Return 0 if the result overflows and does not fit in a 32 bit signed integer
This is my approach:
public class Solution {
public int reverse(int A) {
String ans = " ";
String finalAns = " ";
int range = 2147483647;
if( (A > 0) && (A <= range))
{
ans = String.valueOf(A);
return (Integer.parseInt(new StringBuilder(ans).reverse().toString()));
}
if( (Math.abs(A) > range))
return 0;
else if ( (A > - (range + 1)) && (A < 0) )
{
ans = String.valueOf(Math.abs(A));
if( Math.abs(A) > range)
return 0;
finalAns = (new StringBuilder(ans).reverse().toString());
double d = Double.parseDouble(finalAns);
if( d == (int)d )
return Integer.parseInt( "-" + finalAns);
else
return 0;
}
else
return 0;
}
}
I have following questions regarding my code:
1) Is there a better approach to solve this question?
2) Are there any Java coding conventions that I have violated gravely?
3) Am I doing redundant steps?
A
is anint
and therefore necessarily within the range of an integer. However, you don't check if the reverse of the integer is out of bounds, at least not ifA
is positive, soInteger.parseInt(String)
throws aNumberFormatException
if the reverse integer is too large. \$\endgroup\$ – Stingy Mar 25 '18 at 20:23double
, is, as I already pointed out, only done if the original number is negative. Try your code with any positive 10-digit number that ends with a digit greater than 2, and you will (hopefully) see what I mean. \$\endgroup\$ – Stingy Mar 26 '18 at 7:51