public static int reverseNum(int x){
//给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
// 示例 1:
// 输入: 123
// 输出: 321
// 如何将找到的三位数 变成321? int result = 0 ;用来存储结果 = 3 32 321
//找到最低位 123 % 10 = 3 result * 10 + 3 = 3
// 先第二位 123 / 10 = 12 12 % 10 = 2 result * 10 + 2 = 32
// 最高为 123 / 100 = 1 result * 10 * 1 = 321
//示例 2:
// 输入: -123
// 输出: -321
// int result = 0;
// 找到最低位 -123 % 10 = -3 result * 10 + -3 = -3
//找到第二位 -123 /10 = -12 -12 % 10 = -2 result * 10 + -2 = -32
// 最高位 -123 / 100 = - 1 result * 10 + -1 = -321
// 3:
// 输入: 120
// 输出: 21 int result = 0
// 最低位 120 % 10 = 0 result * 10 + 0 = 0
// 第二位 120 / 10 = 12 12 % 10 = 2 result * 10 + 2 = 2
// 最高位 120 / 100 = 1 result * 10 + 1 = 21
//接收结果
int result = 0 ;
while(x!=0){//123 12 1 120 12 1
//最低位
int bit = x % 10 ; //123%10 = 3 12%10=2 1%10=1 120%10=0 12%10=2 1%10=1
// 去掉最低位
x = x / 10 ;//123/10=12 12/10=1 1/10等于0 循环不执行 120/10=12 12/10=1 1/10等于0 循环不执行
//假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
// int类型的最小值-2147483648/10 = -214748364 最大值 2147483647/10 = 214748364
// 因为result = result * 10 + bit 中*10 所有将int类型的最大值和最小值都处于10
//如果result大于Integer.MAX_VALUE/10 肯定溢出
if(result>Integer.MAX_VALUE/10 || result==Integer.MAX_VALUE && bit>7){
return 0;
}
//如果result小于Integer.MIN_VALUE/10 肯定溢出
if(result>Integer.MIN_VALUE/10 || result==Integer.MIN_VALUE && bit<-8){
return 0;
}
result = result * 10 + bit ;
}
return result;
}
整数反转 公式算法
最新推荐文章于 2022-02-08 20:26:13 发布