题目描述:给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
难度:简单
补充知识:
1.负数的取余和取商
先确定余数,再确定商。余数的准则是商的绝对值尽量靠近0
举例:
除数 | 被除数 | 余数 | 模值 | 分析 |
---|---|---|---|---|
-321 | 10 | -32 | -1 | -321=10*(-32)-1 |
-321 | -10 | 32 | -1 | -321=(-10)*32-1 |
321 | -10 | -32 | 1 | 321=(-10)*(-32)+1 |
321 | 10 | 32 | 1 | 321=10*32+1 |
2.溢出问题的解决方法
解决溢出问题有两个思路,第一个思路是通过字符串转换加try catch的方式来解决,第二个思路就是通过数学计算来解决。
思路:
代码:
class Solution {
public int reverse(int x) {
int ans=0;
while(x!=0){
int pop= x % 10;
if((ans > Integer.MAX_VALUE/10) ||(ans==Integer.MAX_VALUE/10 && pop>8 ) ){
return 0;
}
if((ans < Integer.MIN_VALUE/10) ||(ans==Integer.MAX_VALUE/10 && pop<-7) ){
return 0;
}
ans=ans*10+pop;
x=x/10;
}
return ans;
}
}