给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
public class IntegerReverse {
class Solution {
public int reverse(int x) {
int flag= x>=0?1:-1;
if(x == 0){
return 0;
}else{
long temp = 0;
long result = 0;
x=Math.abs(x);
while(x!=0){
temp = x%10;
result = temp + result * 10;
x/=10;
}
if(result>2147483647 || result <-2147483648){
return 0;
}else{
return (int)(flag*result);}
}
}
}
注意:中间过程result可能超出int的取值范围(java中int4个字节。32位),所以用了long。
自己一开始就是因为全用的 int 类型,导致有些数据在反转过程超了 int 表示范围导致出错。
主要思路:取余 和 整除10.
大佬做法:
public int reverse(int x) {
long n = 0;
while(x != 0) {
n = n*10 + x%10;
x = x/10;
}
return (int)n==n? (int)n:0;
}