题目
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.
思路
先将各位上的数字分别取出依次存放在一个数组里(个位、十位、百位、千位...),然后倒序取出数组即可(...、千位、百位、十位、个位),将结果存在res变量中,for循环得到res变量的值:res += a[i]*10^x。这里要注意的是翻转后溢出的情况——如果用Python编写,由于Python里不用声明变量类型,就算结果大于0x7fffffff也会自动转为长整型,因此直接用|res|>0x7fffffff表示溢出的情况;如果用Java编写,事先声明了int型变量,结果
大于
0x7fffffff则只会截取低32位的数,因此可以用最高位来判断是否溢出,详细设计见代码部分。
代码
Python
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
x_abs = abs(x)
if (x_abs == 2147483648):
return 0
if (x_abs < 10):
return x
base = 1
res,i = 0,0
arr = []
while (x_abs/(base*10) > 0) & (i < 10):
base = pow(10,i)
arr.append((x_abs/base)%10)
i += 1
i -= 1
for j in range(i,-1,-1):
if (arr[j] != 0):
base = pow(10,abs(j-i))
res += arr[j]*base#例如三位数123,原来的个位变百位,百位变个位
if (res < 2147483648):
continue
else:
return 0#溢出处理
if (x < 0):
return -res
else:
return res
Java
public class Solution {
public int reverse(int x) {
int x_abs = Math.abs(x);
//特殊情况的处理
if(x == -2147483648) return 0;
if (x_abs < 10) return x;
int[] arr = new int[11];
int base = 1;
int i,j;
int res = 0;
for(i = 0;x_abs/(base*10) > 0 && i < 10;i++){
//将个位、十位、百位的数依次存在数组里
base = (int)Math.pow(10, i);
arr[i] = (x_abs/base)%10;
}
i -= 1;
for(j = i;j >= 0;j--){
if(arr[j] != 0){
//例如三位数123,原来的个位变百位,百位变个位
base = (int)Math.pow(10, Math.abs(j - i));
res += arr[j]*base;
//如果相加后的最高位是a[j]继续下次循环,否则代表溢出
if(res/base == arr[j]) continue;
else return 0;
}
}
if(x < 0)
return -res;
else
return res;
}
}