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
Constraints:
-231 <= x <= 231 - 1
Approach 01: Math Pop/Push
class Solution {
public:
int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
};
Time Complexity:
- O(log(x)): There are roughly
log10(x)digits inx.
Space Complexity:
- O(1): Constant space used.
class Solution:
def reverse(self, x: int) -> int:
rev = 0
sign = 1 if x >= 0 else -1
x *= sign
while x != 0:
pop = x % 10
x //= 10
if rev > (2**31 - 1) // 10 or (rev == (2**31 - 1) // 10 and pop > 7):
return 0
rev = rev * 10 + pop
return rev * sign
Time Complexity:
- O(log(x)): There are roughly
log10(x)digits inx.
Space Complexity:
- O(1): Constant space used.
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
}
Time Complexity:
- O(log(x)): There are roughly
log10(x)digits inx.
Space Complexity:
- O(1): Constant space used.