7. Reverse Integer
Asked at 14Bloomberg74Google66Apple64Amazon63Microsoft63Meta56tcs67Accenture78EPAM Systems60Cognizant57Capgemini52Infosys45Oracle41LinkedIn20
Problem
Reverse the digits of a 32-bit signed integer x, keeping its sign. Return 0 if the result falls outside [−2³¹, 2³¹ − 1], and assume 64-bit integers aren't available.
Example: 123 → 321; -123 → -321; 120 → 21
Pop digits with % 10 and push with * 10. Before pushing, check that the result stays within [−2³¹, 2³¹−1].
Complexity: O(log x).
class Solution:
def reverse(self, x: int) -> int:
sign = -1 if x < 0 else 1
x, res = abs(x), 0
while x:
x, d = divmod(x, 10)
res = res * 10 + d
res *= sign
return res if -2 ** 31 <= res <= 2 ** 31 - 1 else 0
assert Solution().reverse(123) == 321
assert Solution().reverse(-123) == -321
assert Solution().reverse(120) == 21
assert Solution().reverse(1534236469) == 0
class Solution {
public int reverse(int x) {
int res = 0;
while (x != 0) {
int d = x % 10; // keeps sign in Java
if (res > Integer.MAX_VALUE / 10 || res < Integer.MIN_VALUE / 10) return 0;
res = res * 10 + d;
x /= 10;
}
return res;
}
}
func reverse(x int) int {
res := 0
for ; x != 0; x /= 10 { // Go's % keeps the sign, so negatives just work
res = res*10 + x%10
}
if res < math.MinInt32 || res > math.MaxInt32 {
return 0
}
return res
}