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比较来判断是否越界。
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比较来判断是否越界。
相关文章推荐
- spring源码解析-Webmvc
- 【MongoDB系列】:MongoDB 增删改查应用
- 安卓JNI--Android studio 1.5 JNI开发初探
- QPainter::begin: Paint device returned engine == 0, type: 1
- 八种排序算法总结
- CentOS 5.x和CentOS 6.x限制单个用户线程数上限的不同行为
- Android 笔记
- 开启新园地
- JAVA静态变量
- Autocad 2015如何激活成功
- Xcode单元测试之-lmobilesp
- 将json中的回车转义字符进行处理
- CK610相关术语
- 网络平台交易模式分析
- 聚类算法实践——层次、K-means聚类
- 查看mysql远程访问是否开启?
- JS添加事件和解绑事件:addEventListener()与removeEventListener()
- AutoResetEvent来模拟实现生产消费问题
- java必学必会之方法的重载(overload)
- 租房宝开发心得