leetcode 7 Reverse Integer
2015-10-30 17:14
573 查看
Reverse Integer
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?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
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?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
#include <iostream> #include <math.h> using namespace std; class Solution { public: int reverse(int x) { if (x == 0) { return 0; } int bar = 10; int t = x; int r; int ret = 0; int i = 10; while (t != 0)<span style="white-space:pre"> </span>//将t中的数据拿出,放入ret中 { r = t % bar; if (x == t) { ret = ret + r; } else { if (ret >= 214748365 || ret <= -214748365)<span style="white-space:pre"> </span>//关于其边界问题。 { return 0; } if (ret == 241748364 || ret == -241748364)<span style="white-space:pre"> </span>//关于其边界问题。 { if (r > 8) { return 0; } } ret = ret*i + r; } t = t / bar; }
<span style="white-space:pre"> </span>return ret; } }; int main(int argc, char ** argv) { int x; Solution so; cin >> x; cout << so.reverse(x); return 0; }
相关文章推荐
- 空闲实例v$lock内容小解
- n个人围成一圈数到m和m的倍数时出圈,问剩下的人是谁?在原来的位置是多少?
- 编程入门指南(作者:@萧井陌 @Badger)
- 【完全开源】微信客户端.NET版
- 开始使用mybatis
- Oreacl 查询数据出现中文乱码|配置环境变量
- 收集的35个 jQuery 小技巧/代码片段 转
- DMA及cache一致性的学习心得
- Java 如何将String转化为Int
- IOS 点滴记录
- c#——标准Dispose模式的实现
- Notification and Toast comments
- 充分统计量
- Asp.Net MVC 4 Web API 中的安全认证-使用OAuth
- RHEL 7.1配置Kubernetes集群环境
- VARCHAR2(N CHAR)与VARCHAR2(N)的区别[Oracle基础]
- 负载均衡学习笔记
- java对象转型
- com.alibaba.fastjson.JSONObject.getString耗时问题
- 安卓开发必须收藏的网站