Extract digits from right to left using modulo 10 and construct the reversed integer. Before multiplying by 10, check for 32-bit signed integer overflow bounds [-2^31, 2^31 - 1].
class Solution:
def reverse(self, x: int) -> int:
sign = -1 if x < 0 else 1
x = abs(x)
res = 0
while x > 0:
res = res * 10 + x % 10
x //= 10
res *= sign
if res < -2**31 or res > 2**31 - 1:
return 0
return res
class Solution {
public int reverse(int x) {
long res = 0;
while (x != 0) {
res = res * 10 + x % 10;
x /= 10;
}
if (res < Integer.MIN_VALUE || res > Integer.MAX_VALUE) return 0;
return (int) res;
}
}