Leetcode 07 Integer Reverse问题
2015-08-31 16:39
225 查看
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.
//溢出返回0
一、用大范围的数据来存放结果
二、考虑什么时候会溢出
在计算逆转之后的整数的时候,ret=ret*10+x%10 若在这之前ret>INT_MAX/10;那么执行ret=这句后,必然会溢出。
这部分借鉴http://www.cnphp6.com/archives/64172
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.
//溢出返回0
一、用大范围的数据来存放结果
int reverse(int x) { long long ret=0; int sign=1; if(x<0) { sign=-1; x=-x; } while(x) { ret=ret*10+x%10; x/=10; } ret=sign *ret; if(ret>INT_MAX || ret<INT_MIN) ret=0; return ret; }
二、考虑什么时候会溢出
在计算逆转之后的整数的时候,ret=ret*10+x%10 若在这之前ret>INT_MAX/10;那么执行ret=这句后,必然会溢出。
int reverse(int x) { int res = 0; while (x != 0) { if (abs(res) > INT_MAX / 10) return 0; res = res * 10 + x % 10; x /= 10; } return res; }
这部分借鉴http://www.cnphp6.com/archives/64172
相关文章推荐
- 数学记号
- mybatis学习教程(三)mybatis映射开发规范
- service postgresql initdb [FAILED]
- php代码的一些高效写法
- CentOS Redhat Linux安装 Oracle Client 的注意点
- 轻松实现 网络视频播放器
- [持续更新]HTML5学习笔记(一)
- Linux的inode的理解
- Web服务器的工作原理
- postgresql流复制配置
- double比较大小
- HTTP请求返回状态码详解
- xUtils中的HttpUtils全面注释
- iOS开发系列—Objective-C之内存管理(前辈写的,借鉴了一下,超赞)
- 在cmd命令行下使用cl编译运行C/C++源文件
- Oracle 日期运算1
- 【原创】“借贷宝”砸钱,邀请码 GZZKZK2 (注册成功每人可得20现金,可直接提现)。。。而这只是开始
- 固态硬盘(SSD)原理及相关介绍
- 几种加密算法
- C++ 什么时候只能用intialization list而不能用assignment