MEDIUM
Reverse Integer
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 [-2³¹, 2³¹ - 1], then return 0.
Example
Input:
x = 123
Output:
321
Input:
x = -123
Output:
-321
Input:
x = 120
Output:
21
Constraints
- -2³¹ ≤ x ≤ 2³¹ - 1
Solution: Pop and Push Digits
- Time Complexity: O(log₁₀(x)), since the number of digits in x is proportional to log₁₀(x).
- Space Complexity: O(1), as only a constant amount of extra space is used.
C++
class Solution {
public:
int reverse(int x) {
int r = 0;
while (x) {
if (r > INT_MAX/10 || r < INT_MIN/10)
return 0;
r = r * 10 + x % 10;
x = x/10;
}
return r;
}
};