[LeetCode] Reverse Integer
来源:互联网 发布:ubuntu怎么新建文件夹 编辑:程序博客网 时间:2024/06/07 02:45
题目要求:Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
额外考虑的问题:
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).
Java代码:
public class Solution {
public int reverse(int x) {
int sum=0;
while(x!=0){
int temp=x%10;
sum = sum*10+temp;
x=x/10;
}
return sum;
}
}
确实通过了 但是没有考虑上面提到的特殊情况和边界值的问题,在网上找到了一个这样的例子:
- class Solution {
- public:
- int reverse(int x) {
- // IMPORTANT: Please reset any member data you declared, as
- // the same Solution instance will be reused for each test case.
- const int max = 0x7fffffff; //int最大值
- const int min = 0x80000000; //int最小值
- long long sum = 0;
- while(x != 0)
- {
- int temp = x % 10;
- sum = sum * 10 + temp;
- if (sum > max || sum < min) //溢出处理
- {
- sum = sum > 0 ? max : min;
- return sum;
- }
- x = x / 10;
- }
- return sum;
- }
- };
- LeetCode:Reverse Integer
- LeetCode: Reverse Integer
- [Leetcode] Reverse Integer
- LeetCode : Reverse Integer
- [LeetCode] Reverse Integer
- Leetcode: Reverse Integer
- LeetCode 7 - Reverse Integer
- leetcode 104: Reverse Integer
- Leetcode : Reverse Integer
- 【leetcode】Reverse Integer
- [LeetCode]Reverse Integer
- LeetCode-Reverse Integer
- [leetcode] Reverse Integer
- LeetCode - Reverse Integer
- leetcode之Reverse Integer
- LeetCode | Reverse Integer
- LeetCode: Reverse Integer
- Leetcode: Reverse Integer
- boost ssl
- Android从无知到有知——NO.6
- gdb调试工具命令笔记
- android 将对象存储于本地(内存)
- eclipse在已创建好的目录下创建新项目
- [LeetCode] Reverse Integer
- 唯一的游戏世界
- google protocl buffer 序列化和反序列化的一个例子
- Codeforces Round #216 (Div. 2) E. Valera and Queries (BIT)
- 经纬财富:德兴白银午后操作建议
- ios7,使用boundingRectWithSize方法计算文本正确的size
- 导航栈逻辑上的错误与单例方法
- Java IO流读写文件的几个注意点
- JS-URI处理