Problem
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Solution: Simulation
Reverse digit by digit. Be careful about the overflow and negative numbers (especially in Python)
Time complexity: O(log(x)) ~ O(1)
Space complexity: O(log(x)) ~ O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Author: Huahua class Solution { public: int reverse(int x) { int ans = 0; while (x != 0) { int r = x % 10; if (ans > INT_MAX / 10 || ans < INT_MIN / 10) return 0; ans = ans * 10 + r; x /= 10; } return ans; } }; |
Java
1 2 3 4 5 6 7 8 9 10 11 12 |
class Solution { public int reverse(int x) { int ans = 0; while (x != 0) { int r = x % 10; if (ans > Integer.MAX_VALUE / 10 || ans < Integer.MIN_VALUE / 10) return 0; ans = ans * 10 + r; x /= 10; } return ans; } } |
Python3
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Solution: def reverse(self, x): min_val = -(2**31); max_val = 2**31 - 1; sign = -1 if x < 0 else 1 x = abs(x) ans = 0 while x != 0: ans = ans * 10 + (x % 10) x //= 10 ans *= sign if ans > max_val or ans < min_val: return 0 return ans |