整数反转
1、参考资料
https://leetcode-cn.com/problems/reverse-integer/
2、题目要求
题目描述
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32
位的有符号整数,如果反转后整数溢出那么就返回 0
。
3、代码思路
求整数各位(个位、十位、百位、…)的值
对于一个整数 int x = 123
,我们分别求得其个位、十位、百位的数值,才能对其进行翻转
算法步骤:int digit = x % 10; x = x / 10;
,即每次对 10
取余,取余后抹去低位(整体向右移),直到 x == 0
时,算法停止
如何判断翻转后的整数是否将要溢出?
我们使用 result
记录翻转后的整数,curDigit
记录原整数当前位的值,溢出可分两种:向上溢出和向下溢出
向上溢出的条件:第一,result * 10
后直接溢出;第二:result * 10
后并未溢出,但 result * 10 + curDigit
溢出,这种情况使用 Integer.MAX_VALUE
进行判断
向下溢出的条件:第一,result * 10
后直接溢出;第二:result * 10
后并未溢出,但 result * 10 + curDigit
溢出,这种情况使用 Integer.MIN_VALUE
进行判断
4、代码实现
代码
/**
* @ClassName ReverseDemo
* @Description TODO
* @Author Heygo
* @Date 2020/9/3 17:38
* @Version 1.0
*/
public class ReverseDemo {
public static void main(String[] args) {
Solution solution = new Solution();
int reverse = solution.reverse(1463847412);
System.out.println(reverse);
}
}
class Solution {
public int reverse(int x) {
int result = 0;
// x != 0:说明 x 的高位还有值
while (x != 0) {
int curDigit = x % 10; // 当前位的值
x /= 10; // x 整体右移
if ((result > Integer.MAX_VALUE / 10) || (result == Integer.MAX_VALUE / 10 && curDigit > Integer.MAX_VALUE % 10)) {
// 如果翻转后的整数溢出(大于 Integer.MAX_VALUE)
result = 0;
break;
} else if ((result < Integer.MIN_VALUE / 10) || (result == Integer.MIN_VALUE / 10 && curDigit < Integer.MIN_VALUE % 10)) {
// 如果翻转后的整数溢出(小于 Integer.MIN_VALUE)
result = 0;
break;
}
result = result * 10 + curDigit; // 加上低位
}
return result;
}
}