给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
示例 1:
输入:x = 123
输出:321
示例 2:
输入:x = -123
输出:-321
示例 3:
输入:x = 120
输出:21
示例 4:
输入:x = 0
输出:0
来源:力扣(LeetCode)
class Solution {
public int reverse(int x) {
if(x==0)
return 0;
long target=0;
int m=0;
int flag=1;
int num=0;
if(x<0)
flag=-1;
x=Math.abs(x);
if(x%10==0){
num++;
x/=10;
while(x%10==0){
num++;
x/=10;
}
}
while(x!=0){
m=x%10;
target=target*10+m;
x/=10;
}
if(flag==-1){
return (-1)*((int)target==target?(int)target:0);
}
else{
return (int)target==target?(int)target:0;
}
}
}