您的位置:首页 > 其它

leetcode第七题:Reverse Integer

2015-12-03 14:25 387 查看
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.

integer:范围:-2^31~2^31-1;

C++知识:

short为半个机器字长

int为一个机器字长

而long类型为一个或者2个机器字长。

所以由于int一般为32位并不能表示在-2^31~2^31-1的数,所以我们选择long类型来计算。

代码如下:

class Solution {
public:
int reverse(int x) {
int max=0x7fffffff;
int min=0x80000000;
<span style="color:#FF0000;"> long sum=0;</span>
int temp;
while(x!=0)
{
temp=x%10;
sum=10*sum+temp;
if(<span style="color:#FF0000;">sum>max || sum<min</span>) return 0; ;
x=x/10;
}
return sum;
}
};

对于反转interger,方法是每次读取其当前x的个位数,然后放到sum的末位,此时sum等于在十进制的上面左移一位,即原先的sum*10再加上x的个位数即得到新的sum值。
通过对x进行x=x/10的操作,使得x右移一位,删除了x的个位数(到了小数部分被“强制类型转换”变没了)。

sum是long类型的,有能力表示-2^31~2^31-1范围以外的值,所以可以通过跟max和min比较来判断是否越界。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: