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.
本菜鸟:
class Solution {
public int reverse(int x) {
int[] a = new int[10];
int wei = 1;
int flag = 0;
if(x==-2147483648) return 0;
if(x<0) {x = -x; flag = 1;}
for(int i = 0;i < 10 ;i++){
a[i] = x%10;
x = x/10;
if(x>0) wei++;
}
x = 0;
for(int j = 0;j < wei;j++) {
if(x < Integer.MAX_VALUE/10 ||x == Integer.MAX_VALUE/10) x = x*10+a[j];
else return 0;
}
if(flag==0) return x; else return -x;
}
}
这道LeetCode上面简单题的前几题,考查的内容却是相当的多。这个问题本身很简单。
难点1:-2^31 *(-1)= ?
经过测试,结果为-2^31。如果按照上述代码的写法,必须要考虑这种情况。
难点2:
在生成x的reverse的时候,要考虑数值是否越界的问题。
大神的代码:
@author LyneDefense
class Solution {
public int reverse(int x) {
int res = 0;
int temp = 0;
while(x != 0){
int tail = x%10;
temp = res*10 +tail;
if((temp-tail)/10 !=res) //判断res是否溢出
return 0;
res = temp;
x = x/10;
}
return res;
}
}
这里面通过(temp-tail/10 )==res来判断temp是否溢出,实在是一种非常高明的手段,普通人估计也不敢这么写。数据溢出以后,程序并不会报错,只是结果不对而已。并且,可以看出,按照正负号分类实在是我们一厢情愿而已。
官方代码:
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
}