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 [-231, 231 - 1]
, then return 0
.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123 Output: 321
Example 2:
Input: x = -123 Output: -321
Example 3:
Input: x = 120 Output: 21
JAVA
public class Solution {
public int reverse(int x) {
int result = 0;
while (x != 0) {
int tail = x % 10;
int newResult = result * 10 + tail;
// If overflow exists, the new result will not equal previous one.
/*
result = 998765432
newResult = 1397719729 // here the program will do a cast, meaning overflow
*/
if ((newResult - tail) / 10 != result) {
return 0;
}
result = newResult;
x = x / 10;
}
return result;
}
}
C++
class Solution {
public:
int reverse(int x) {
if (x == INT_MIN) return 0;
int r = 0, sign = x >= 0 ? 1 : -1, y = sign * x, p = 1;
while (y) {
y /= 10;
if (y) p *= 10;
}
x = sign * x;
while (x) {
int d = x % 10;
x /= 10;
if ((INT_MAX - r) / p < d) return 0;
r += p * d;
p /= 10;
}
return sign * r;
}
};
PYTHON
class Solution:
def reverse(self, x: int) -> int:
y = int(str(abs(x))[::-1])
res = -y if x < 0 else y
return 0 if res < -(2**31) or res > 2**31 - 1 else res
JAVASCRIPT
var reverse =
function (x) {
let res = 0;
while (x) {
res = res * 10 + (x % 10);
x = ~~(x / 10);
}
return res < Math.pow(-2, 31) || res > Math.pow(2, 31) - 1 ? 0 : res;
};