Question
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.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
Java Code
版本一:通过字符数组转换
public int reverseInteger(int x) {
char[] s = String.valueOf(x).toCharArray();
char temp;
if(-9 < x && x < 9)
return x;
else if(x < 0)
for(int i=1; i <= (s.length - 1)/2; ++i) {
temp = s[i];
s[i] = s[s.length - i];
s[s.length - i] = temp;
}
else
for(int i=0; i <= (s.length - 1)/2; ++i) {
temp = s[i];
s[i] = s[s.length - i - 1];
s[s.length - i - 1] = temp;
}
long lx = Long.parseLong(String.valueOf(s));
return (lx > Integer.MAX_VALUE || lx < Integer.MIN_VALUE) ? 0 : (int)lx;
}
版本二:利用StringBuffer.reverse() 方法
public int reverseInteger(int x) {
if(x >= -9 && x <= 9) return x;
long lx = (x<0) ?
Long.parseLong("-" + new StringBuffer(String.valueOf(x).substring(1)).reverse()) :
Long.parseLong(new StringBuffer(String.valueOf(x)).reverse().toString());
return (lx > Integer.MAX_VALUE || lx < Integer.MIN_VALUE) ? 0 : (int)lx;
}
说明
由于基本数据类型的包装类可以直接将字符串解析为有符号的数值,所以Tips中提示的整数末尾数字为0导致的问题在java中不存在
整型数值反转后可能会超出其范围,所以可以使用包装类Long进行字符串解析
以上两种方法写起来比较简单但效率都不高,本题也可以采用另一种高效的思路避免借助于字符或字符串处理,即依次取出原整数的个位、十位。。。,然后依次作为新整数的最高位、次高位。。。
更新
2016.03.31
public int reverseInteger(int x) {
if(x >= -9 && x <= 9) return x;
long lx = 0;
while(x != 0) {
lx = lx * 10 + x % 10;
x /= 10;
}
return (lx > Integer.MAX_VALUE || lx < Integer.MIN_VALUE) ? 0 : (int)lx;
}