首页 > 代码库 > Reverse Integer
Reverse Integer
原题链接: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.
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.
原本是有buge(不考虑溢出)也能通过的,可是如今不行了。须要考虑溢出问题
以下是我用Java写的,AC通过。
。(当中推断溢出的部分參考了他人代码。链接在此:http://blog.csdn.net/stephen_wong/article/details/28779481)
public class Solution { public int reverse(int x) { int res = 0; int flag = 0; if(checkOverflow(x)) { return 0; } else { if(x < 0) { flag = 1; x = -x; } while(x>0) { res = x % 10 + res * 10; x /= 10; } if(flag == 1) { return -res; } return res; } } public static boolean checkOverflow(int x) { if(x/1000000000 == 0) { //x的绝对值小于1000000000。不越界 return false; } else if(x == Integer.MIN_VALUE) {//Integer.MIN_VALUE = http://www.mamicode.com/-2147483648。反转后越界,也没法按下述方法取绝对值(以下绝对值的方法相当于对排除了正、负数的影响)>
Reverse Integer