[Leetcode] reverse integer 反转整数

时间:2023-03-09 00:08:07
[Leetcode] reverse integer 反转整数

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

题意:将一个整数反转。

思路:这题有几个要注意的地方:一、正负号;二、反转后的结果是否溢出。第二点很重要,关于这点题目中有详细的说明。这里有两种解法方法:

方法一:改变返回结果的变量类型为long long ,这样,若是最终计算的结果超过INT_MAX,就返回0;否则,结构符号输出即可。

代码如下:

 class Solution {
public:
int reverse(int x)
{
long long res=;
int cur=abs(x); while(cur>)
{
res=res*+cur%;
cur/=;
}
if(res>INT_MAX) return ;
return x>=?res:-res;
}
};

方法二:不用改变返回的变量类型,在while循环中,在计算res之前,若res>INT_MAX/10,就返回0,因为若是大于,则后续的计算中乘以10 了,还是会大于,所以提前返回。代码如下:

 class Solution {
public:
int reverse(int x)
{
int res=;
int cur=abs(x); while(cur>)
{
if(res>INT_MAX/) return ;
res=res*+cur%;
cur/=;
} return x>=?res:-res;
}
};

在LeetCode上测试时,第二种方法,明显好些。