二、整数反转
给你一个 32 位的有符号整数 x ,返回 x 中每位上的数字反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
1、我的
class Solution {
public int reverse(int x) {
boolean check=false;
if(x<0){
x=-x;
check=true;
}
int minnum=-2147483648;
int maxnum=2147483647;
long y=0;
while(x!=0){
y=y*10+x%10;
x=x/10;
}
if(y<=minnum || y>=maxnum){
return 0;
}
if(check){
y=-y;
}
int m=(int)y;
return m;
}
}
2、官方的
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;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/reverse-integer/solution/zheng-shu-fan-zhuan-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
3、评论区看见一个还不错的
public int reverse(int x) {
int ans = 0;
while (x != 0) {
if ((ans * 10) / 10 != ans) {
ans = 0;
break;
}
ans = ans * 10 + x % 10;
x = x / 10;
}
return ans;
}