【leetcode】7. Reverse Integer
2016-07-07 22:38
274 查看
一、题目描述
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.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
题目解读:将数字反转,注意溢出的情况,溢出的时候返回0
思路:反转比较简单,特别注意溢出的情况。int型最大值INT_MAX和最小值INT_MIN,头文件是<limits.h>。注意result最好定义为long,定义为int后面为报错,因为会有溢出的数。
c++代码(8ms,48.11%)
其他代码:
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.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
题目解读:将数字反转,注意溢出的情况,溢出的时候返回0
思路:反转比较简单,特别注意溢出的情况。int型最大值INT_MAX和最小值INT_MIN,头文件是<limits.h>。注意result最好定义为long,定义为int后面为报错,因为会有溢出的数。
c++代码(8ms,48.11%)
class Solution { public: int reverse(int x) { long result=0; while(x){ result = result*10 + x%10; x=x/10; }//while //防止溢出 if(result > INT_MAX || result < INT_MIN) { result = 0; } return result; } };
其他代码:
class Solution { public: int reverse(int x) { long long res = 0; while(x) { res = res*10 + x%10; x /= 10; } return (res<INT_MIN || res>INT_MAX) ? 0 : res; } };
相关文章推荐
- 深入理解Java虚拟机--对象访问
- getCacheDir()和getFilesDir()
- 新项目新技术
- 区块链向前走:步步奇葩,还是步步生花?
- innodb 锁分裂继承与迁移
- C#基础
- CSS样式初始化
- Java lock锁
- 279. Perfect Squares
- SCU2016-02 Q题区间dp
- 学无止境
- CodeForces 689D-Friends and Subsequences
- Hbase关于Java常用API举例
- Java回调机制
- 【基础】PNP三极管导通条件____很具代表性
- unittest学习记录
- InterlliJ 定制Getter and Setter分享
- Minimum Window Substring
- android CoordinatorLayout使用
- 剑指offer--6.旋转数组的最小数字