我正试图解决7.在leetcode https://leetcode.com/problems/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;
}
} 我搞错了四个测试用例。其中之一是:
示例
Input: 1534236469
Output : 1056389759
Expected: 0 发布于 2022-01-15 14:39:01
您的问题是溢出在num变量中,您没有检查它。通过添加检查以确保计算在执行num = num*10+a之前不会溢出,您可以在必要时返回0。
另外,你没有正确处理负数。预先检查一个负数可以让你处理一个正数,然后否定结果。
class Solution {
public int reverse(int x) {
int num=0;
Boolean negative = false;
if (x < 0) {
x = -x;
negative = true;
}
while(x!=0){
int a=x%10;
// Check if the next operation is going to cause an overflow
// and return 0 if it does
if (num > (Integer.MAX_VALUE-a)/10) return 0;
num=num*10+a;
x=x/10;
}
return negative ? -num : num;
}
} 发布于 2022-01-15 14:23:13
你选择的方法并不遥远。
x是否在无符号整数的范围内。但是他们要求检查x-反转。如果将结果num聚合为long类型的变量,而拒绝/零答案(如果反转后超出了无符号int的界限),则可以解决这两个问题。
您可以使用Math.addExact(a,b)、Math.multiplyExact(a,b)和try-catch在溢出时立即退出。
发布于 2022-01-15 14:48:30
输入: 123输出: 321输入:-123输出:-321输入: 120输出: 2
类解决方案{ public: int反向(Int x) {
int rev = 0;
constexpr int top_limit = INT_MAX/10;
constexpr int bottom_limit = INT_MIN/10;
while (x) {
if (rev > top_limit || rev < bottom_limit)
return 0;
rev = rev * 10 + x % 10;
x /= 10;
}
return rev;
}};
https://stackoverflow.com/questions/70722143
复制相似问题