LeetCode | Reverse Integer
2016-08-07 11:16
393 查看
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.
反转一个int数字,需要注意的是INT_MAX和INT_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.
反转一个int数字,需要注意的是INT_MAX和INT_MIN的处理
class Solution { public: int reverse(int x) { int temp= x; //我知道了,INT_MIN绝对值比INT_MAX大1 //所以不可以一上来就将x取绝对值 // printf("x %d sign %d temp %d\n",x,sign,temp); int sum=0; while(temp){ //判断越界 if((INT_MAX/10 < sum) || (INT_MAX/10==sum && ((INT_MAX%10) < (temp%10)))) return 0; if((INT_MIN/10 > sum) || (INT_MIN/10 ==sum && ((INT_MIN%10 )>(temp%10) )) ) return 0; sum=sum*10+temp%10; temp/=10; } return sum; } };
相关文章推荐
- keepalived+LVS+apache双机搭建高可用负载均衡web服务
- 大数据系列修炼-Scala课程02
- 前端工程化的理解
- Android Studio使用心得与技巧
- spring升级版springBoot
- MPTCP 源码分析(二) 建立子路径
- Java中的异常 Exception
- Spring的三种注入方式
- HDU 5806 NanoApe Loves Sequence Ⅱ (尺取法)
- 程序员职业规划——管理篇
- Android获取通讯录联系人,右侧字母滑动索引
- spring lookup method 注入
- Android CTS Verifier bug - Streaming Video Quality Verifier
- Leecode题集——sqrtx
- Add Two Numbers_leetcode_#2
- Javascript 设置Cookie
- HDU5806 NanoApe Loves Sequence Ⅱ
- Java异常处理和设计
- mysql入门
- Git常用命令快速回顾(一)