0
点赞
收藏
分享

微信扫一扫

[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?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

这道题目难度easy,难点在于溢出。我第一次写是先计算reverse值再与整型边界值比较,好处是一目了然,坏处是使用了long型变量浪费了空间。

public class Solution {
public int reverse(int x) {
//require
int temp=0;
long ans=0,test=0;
long max=0x7fffffff,min=0x80000000;
//invariant
while(x!=0){
temp=x%10;
test=ans*10+temp;
if(test>max||test<min)
return 0;
ans=ans*10+temp;
x=x/10;
}
//ensure
return (int)ans;
}
}

【注意】
这里ans必须为long,不能为int,否则ans*10一旦溢出,​​​test=ans*10+temp;​​中是按溢出的结果与temp相加。具体参考:​​java int 乘法溢出问题​​

后来我看discuss的一篇写得很好:​​My Java Solution 2ms - easy understand​​​,主要利用了整型变量的范围特点节省了空间。整型变量的范围是 [-2,147,483,648 2,147,483,647],在本次循环开始就进行判断,一旦上一次的​​ans>max/10||ans<min/10​​,就可以判断本次必定要溢出。有同学可能要问,如果最终的结果是max+1,不是也溢出了吗,但是它没有被判定啊。你要明白,如果结果是max+1,那溢出的就是输入参数x,所以不用担心。

public class Solution {
public int reverse(int x) {
//require
int temp=0;
int ans=0,test=0;
//invariant
while(x!=0){
if(ans>Integer.MAX_VALUE/10||ans<Integer.MIN_VALUE/10)
return 0;
ans=ans*10+x%10;
x=x/10;
}
//ensure
return ans;
}
}

【注意】
这个方法对于范围值的最大值有要求:最高位要比最低位小。
你看,如果范围是[-9002 9001],这个方法就不灵了,所以有局限性,不能算是个广义方法。


举报

相关推荐

0 条评论