LeetCode/solutions/7. Reverse Integer.md

48 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [7. Reverse Integer](https://leetcode.com/problems/reverse-integer/description/)
# 思路
翻转一个整数,这题主要就是考察如何判断溢出(只能是[2^31, 2^31 1], 即[-2147483648, 2147483647])。题目要求只能用32位的整数所以就不能使用long long型了下面的代码给出两种比较巧妙的判断溢出的方法。
另外注意对负数运用取余操作符"%":
* C++G++ 编译): cout << (-7) % 3; // 输出 -1
* Java1.6 System.out.println((-7) % 3); // 输出 -1
* Python 3.6>>> (-7) % 3 // 输出 2
# C++
## 方法一
```
class Solution {
public:
int reverse(int x) {
int ans = 0;
while (x) {
// 如果接下来的代码会溢出的话此时ans肯定等于正负214748364
int temp = ans * 10 + x % 10;
// 若上面的代码未溢出temp / 10 肯定等于ans否则溢出
if (temp / 10 != ans) // 巧妙的判断是否溢出的方法
return 0;
ans = temp;
x /= 10;
}
return ans;
}
};
```
## 方法二(较方法一更快)
```
class Solution {
public:
int reverse(int x) {
int ans = 0, tmp;
while (x) {
tmp = x % 10;
// INT_MAX / 10 = 214748364
if(abs(ans) > INT_MAX / 10) return 0; // 此时ans * 10肯定溢出
if(abs(ans) == INT_MAX / 10){
if(tmp <= -9 || tmp >= 8) return 0; // ans * 10 不溢出但是加上tmp溢出
}
ans = ans * 10 + tmp;
x /= 10;
}
return ans;
}
};
```