007 Reverse Integer [Leetcode]
2015-11-11 16:31
465 查看
题目内容:
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.
没什么难度,只要考虑周全异常情况处理即可。
代码:
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.
没什么难度,只要考虑周全异常情况处理即可。
代码:
class Solution { public: int reverse(int x) { char num[12]; int result(0); int length = sprintf(num, "%d", x); bool allZero = true; int start(0), end(length-1); if(num[0]=='-' || num[0]=='+') ++start; while(start < end) { if(num[end] != '0') allZero = false; char temp(num[start]); if(!allZero) { num[start++] = num[end]; num[end--] = temp; } else num[end--] = '\0'; } sscanf(num, "%d", &result); char cmp[12]; sprintf(cmp, "%d", result); if(strcmp(cmp, num) == 0) return result; return 0; } };
相关文章推荐
- iOS读写本地文件
- 如何用iptables开放一段端口
- 用户权限分类
- spring aop一些名词的理解
- js 动态添加table
- Genesis不能运行Perl编译后的脚本
- [置顶] android高性能编程中需要注意的问题
- 代码解答(1)
- JavaScript中获取Radio被选中的值
- Android编程之监听器的实现方法
- 使用Java和JS访问cookies
- 无奈,想问问题,但是问题页的字数有限,所以在此贴上代码!
- hdu 2896 病毒侵袭
- 电子书《寿康宝鉴》(附白话)全文连载(一)
- 英语学习相关
- eclipse进行Web开发环境配置-设置自动部署WEB项目到我们配置的tomcat服务器
- 20135329 李海空家庭作业 6.38
- Silverlight实用窍门系列:57.Silverlight中的Binding使用(二)-数据验证
- sicily 1194. Message Flood
- windows学习记录之MFC编程之自定义消息映射