【LeetCode 7: Reverse Integer】
2015-09-27 13:00
344 查看
Description:
Reverse digits of an integer.Example1: x = 123, return 321
Example2: x = -123, return -321
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) { int ans = 0; while(x) { if(ans > INT_MAX / 10 || (ans == INT_MAX / 10 && (x%10) > INT_MAX % 10) || ans < INT_MIN / 10 || (ans == INT_MIN/10 && (x%10)<INT_MIN % 10) ) return 0; ans = ans * 10 + x % 10; x /= 10; } return ans; } };
代码已测试通过
思考与小结:
这道题不要尝试将输入的数先转换位整数再进行运算,因为可能负数在转换为整数的时候就可能发生了溢出,但实际上应得到的结果不应该是溢出是的结果0;因此直接对原数进行操作即可;相关文章推荐
- 地址消毒
- 浏览器找不到链接解决方案
- FL2440 2.6.28 SD卡驱动BUG解决
- mysql 加锁 解锁 页表行锁
- 条款43:学习处理模板化基类内的名称
- java web.xml listener servlet 和filter加载顺序
- Linux那些事读书笔记
- Android实现向Launcher添加快捷方式的方法
- 输入子系统分析
- 检测到有潜在危险的 Request.Form 值
- 下列的式子成立,采用的是几进制表示的
- WIFI网卡使用分析
- Linux内核学习之编译篇
- 分层分离的总线驱动模型分析
- Top 20 Java Libries Used by Github's Most Popular Java Projects
- 每周一个算法(1)---倒排索引
- Android浏览器控件WebView简单小实例
- spring_150909_hibernate_id_table
- 测试11班中秋晚会圆满结束
- C/C++ 一元二次方程