7. Reverse Integer - Medium
前往題目
想法
- 以為可以用
bit manipulation
思路
- 每次取一位,並去除
x
一位 - 檢查溢出
- 沒問題就加入
result
這題的關鍵是怎麼判斷溢出,沒有overflow
的話就是easy
到不行的題目
如何判斷overflow
:
- 判斷
result
是否大於Integer.MAX_VALUE / 10
,先不看最後一位,如果大於就不用看最後一位,因為確定他們位數相同;負數則判斷是否小於Integer.MIN_VALUE / 10
,同理 - 如果前面都一樣就比較最後一位,正數就看是否
result
最後一位大於Integer.MAX_VALUE
的最後一位;負數就是看是否小於
Code
class Solution {
public int reverse(int x) {
final int MAX = Integer.MAX_VALUE;
final int MIN = Integer.MIN_VALUE;
int res = 0;
while (x != 0) {
// Obtain last digit
int digit = x % 10;
// Get rid of last digit
x = x / 10;
// Check positive overflow
if (res > MAX / 10 ||
(res == MAX / 10 && digit > 7)) {
return 0;
}
// Check negative overflow
if (res < MIN / 10 ||
res == MIN / 10 && digit < -8) {
return 0;
}
// Done checking, add to result
res = (res * 10) + digit;
}
return res;
}
}
7. Reverse Integer - Medium
https://f88083.github.io/2024/01/15/7-Reverse-Integer-Medium/