跳到主要内容

7 整数反转

https://leetcode.cn/leetbook/read/top-interview-questions-easy/xnx13t/

https://leetcode.cn/problems/reverse-integer/description/

cost: 10m58s

class Solution {
public:
int reverse(int x) {
if (x < 0) {
if (x == (-0x7FFFFFFF - 1)) {
return 0;
}
return -this->reverse(-x);
}
int threshold = 0x7FFFFFFF / 10;
int r = 0;
while (x > 0) {
if (r > threshold) {
return 0;
}
r *= 10;
r += x % 10;
x /= 10;
}
return r;
}
};
  • 时间复杂度:O(log(n))
  • 空间复杂度:O(1)