0%

7. Reverse Integer

O(n) time O(1) space

1
2
3
4
5
6
7
8
9
10
class Solution:
def reverse(self, x: int) -> int:
res, MAX = 0, (1 << 31) - 1
sign = -1 if x < 0 else 1
x = abs(x)
while x > 0:
res = res * 10 + x % 10
x //= 10
if res > MAX: return 0
return res * sign

这道题不需要保存负号,直接转即可

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int reverse(int x) {
long res = 0;
while (x) {
res = res * 10 + x % 10;
x /= 10;
if (res < INT_MIN || res > INT_MAX) return 0; // 只要invalid就返回
}
return res;
}
};

O(n) time O(n) space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int reverse(int x) {
if (x == INT_MIN || x == 0) return 0;
int sign = x < 0 ? -1 : 1;
x = abs(x);
string s = to_string(x);
while (!s.empty() && s.back() == '0') s.pop_back();
long res = 0;
for (auto rit = s.rbegin(); rit != s.rend(); ++rit) {
res = res * 10 + *rit - '0';
if (res > INT_MAX) return 0;
}
return sign * res;
}
};