【发布时间】:2022-01-15 14:04:58
【问题描述】:
我正在尝试解决 leetcode https://leetcode.com/problems/reverse-integer/ 上的 7.Reverse Integer。
给定一个有符号的 32 位整数 x,返回 x 的数字反转。如果反转 x 导致值超出有符号 32 位整数范围 [-2^31, 2^31 - 1],则返回 0。
示例 1:
Input: x = 123
Output: 321
我对上述问题的解决方案是
class Solution {
public int reverse(int x) {
int num=0;
if(x>Integer.MAX_VALUE||x<Integer.MIN_VALUE) return 0;
while(x!=0){
int a=x%10;
num=num*10+a;
x=x/10;
}
return num;
}
}
我弄错了 4 个测试用例。其中之一是:
示例
Input: 1534236469
Output : 1056389759
Expected: 0
【问题讨论】:
-
您需要考虑整数溢出以及如何避免它。 0 的预期答案告诉您简单的反转超出范围。
-
"如果反转 x 导致值超出有符号的 32 位整数范围 [-2^31, 2^31 - 1],则返回 0。"
标签: java algorithm integer reverse