LeetCode 7. Reverse Integer(反转整数)
2016-05-19 03:54
393 查看
原题网址:https://leetcode.com/problems/reverse-integer/
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.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
方法:不断求余和乘以十,注意溢出。
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.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
方法:不断求余和乘以十,注意溢出。
public class Solution { public int reverse(int x) { boolean negative = x < 0; if (negative) x = -x; long r = 0; while (x>0) { r = r * 10 + x % 10; x /= 10; } if (negative) r = -r; if (r > Integer.MAX_VALUE || r < Integer.MIN_VALUE) return 0; return (int)r; } }
相关文章推荐
- LeetCode 6. ZigZag Conversion(之字形)
- 更换证书后 打包异常 "UUID not found"/ "xxxx描述文件 not found"
- Drupal 登录提示Unrecognized Username and Password. 【已解决】
- 贝叶斯推断--Gibbs Sampling
- LeetCode 5. Longest Palindromic Substring(最长回文子串)
- lua-洗牌算法
- html5无法获取页面的输入值
- 燃尽图
- 在Pythonanywhere上部署Django
- python 的import机制2
- YAML初探
- NYOJ-19-擅长排列的小明
- Xsolla 有15项新功能添加到了4月份的日志中。
- 关于 Java连接sql的转载
- SQL Server删除重复行
- [Ruby笔记]6. Ruby load require 使用对比
- PTA Review of Programming Contest Rules
- 万能的sdk工具!
- Spring 事务机制详解
- JSP+JavaScript实现图片切换