Given a 32-bit signed integer, we want to generate the 32-bit signed integer obtained by reversing the digits of the original number. Incase, the result is beyond the range of a 32-bit signed integer, we return 0.
To reverse a number we need to progressively extract the mod 10 and keep pushing into our new by first multiplying it by 10 and then adding the obtained digit from the original number. This is equivalent to extracting the digit, right shifting the given number, left shifting the new number and adding the digit.
class Solution {
public int reverse(int x) {
long soln = 0;
while(x != 0) {
soln = 10 * soln + x % 10;
x /= 10;
}
if ((soln > Integer.MAX_VALUE) || (soln < Integer.MIN_VALUE))
return 0;
return (int)soln;
}
}
The above code uses the constants from Integer class in java.lang package. However, this logic fails if we are given a 64-bit signed number, as we will not have a larger sized integer. A better solution based on the exception handling is given below.
class Solution {
public int reverse(int x) {
int soln = 0;
try {
while(x != 0) {
soln = Math.multiplyExact(soln, 10);
soln = Math.addExact(soln, x % 10);
x /= 10;
}
} catch (ArithmeticException e) {
soln = 0;
}
return soln;
}
}
Comments
Post a Comment