题目
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
题解:
由题意我们可以得到,将一个输入的10进制整数反转,得到另一个十进制整数,如果末尾为0则去掉,如120变21,如果反转后32位整数溢出,那么返回0。
这里我们首先确定反转的算法:用一个数组存下每一个位,然后按照10进制整数的算法求出反转后32为整数的值。但是这里有一个问题,如何判断溢出呢?这里我们用一个64位的整数来保存反转后的值,如果它大于最大整数或者小于最小整数则返回0。
具体实现代码如下:
class Solution {
public int reverse(int x) {
if(x == 0) return 0;
int[] digits = new int[15]; // 保存求出来的各位数字
int temp = x,i = 0;
boolean sign = (x>0); // 用于判断符号
int t = temp%10; // 这里和下面一个while都是用于去除最后的0
while(t==0){
temp/=10;
t=temp%10;
}
while(temp!=0){ // 得到保存的每一位的数字
t = temp%10;
digits[i++]=t;
temp /=10;
}
if(sign){ // 如果是正数
long ret = 0;
int base = 10;
for(int j = 0;j < i;j++){ // 迭代求出反转后的值
ret = ret*base+digits[j];
}
if(ret <= Integer.MAX_VALUE){
return (int)ret;
}else return 0;
}else{ // 如果是负数
long ret = 0;
int base = 10;
for(int j = 0;j < i;j++){
ret = ret*base+digits[j];
}
int minvalue = Integer.MIN_VALUE;
if(ret >= minvalue){
return (int)ret;
}else return 0;
}
}
}