Maths: Reverse a number

1 min read
Reverse a number
Given a signed 32-bit integer x
, return x
with its digits reversed. If reversing x
causes the value to go outside the signed 32-bit integer range [-2<sup>31</sup>, 2<sup>31</sup> - 1]
, then return 0
.
class Solution {
public int reverse(int x) {
boolean checkSignFlag = false;
if(x<0) {
checkSignFlag = true;
x = -x;
}
long reverse = 0;
while(x>0) {
int digit = x%10;
reverse = reverse * 10 + digit;
x = x/10;
}
if(reverse > Integer.MAX_VALUE || reverse<Integer.MIN_VALUE){
return 0;
}
if ( checkSignFlag ) {
return (int)(-1 * reverse);
} else {
return (int)reverse;
}
}
}
Input
x = 1534236469
Output
1056389759
Expected
0
Time complexity
O(log n)
Space complexity
O(1)
Time taken
0
Subscribe to my newsletter
Read articles from Ctangent directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
