題目
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
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.
思路
代碼
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;
}
}