LeetCode - 7 Reverse Integer

作者 QIFAN 日期 2016-08-31
LeetCode - 7 Reverse Integer

Difficulty:Easy

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.

代码

My Solution (really lame)

public class Solution {
public int reverse(int x) {
if(x > -10 && x < 10) return x;
if(x > 2147483647 || x < -2147483647) return 0;
String MAX_INT = "2147483647";
int sign = x < 0 ? -1 : 1;
StringBuilder num = new StringBuilder(String.valueOf(Math.abs(x)));
num.reverse();
while(num.charAt(0)=='0') {
num.deleteCharAt(0);
}
if(MAX_INT.length()==num.length() && num.toString().compareTo(MAX_INT)>0 ) return 0;
return Integer.parseInt(num.toString()) * sign;
}
}

A GOOD ONE

Source: https://discuss.leetcode.com/topic/6104/my-accepted-15-lines-of-code-for-java

public int reverse(int x)
{
int result = 0;
while (x != 0)
{
int tail = x % 10;
int newResult = result * 10 + tail;
if ((newResult - tail) / 10 != result) // 如果reverse超了integer范围,则会变成MIN_INTEGER,即-2147483647
{ return 0; }
result = newResult;
x = x / 10;
}
return result;
}

原题链接:https://leetcode.com/problems/reverse-integer/