[LeetCode] 7. 整数反转(java实现)秦九韶算法
1. 题目
2. 读题(需要重点注意的东西)
思路:
抠出每一位,再倒置,抠出来每一位倒置转换成 int ,可用秦九韶算法
秦九韶算法: res = res * 10 + x % 10;
溢出判断:
- 当res < 0 时:
res* 10 + res% 10 < Integer.MAX_VALUE
===>res < (Integer.MAX_VALUE - x % 10) / 10
- 当res > 0 时:
res* 10 + res% 10 > Integer.MIN_VALUE
===>res >(Integer.MIN_VALUE - x % 10) / 10
3. 解法
---------------------------------------------------解法---------------------------------------------------:
class Solution {
public int reverse(int x) {
int res = 0;
while (x != 0){
// 溢出判断
if (res > 0 && res > (Integer.MAX_VALUE - x % 10) / 10) return 0;
if (res < 0 && res < (Integer.MIN_VALUE - x % 10) / 10) return 0;
// 把每一位抠出来,倒置
res = res * 10 + x % 10;
// 除去最后一位
x /= 10;
}
return res;
}
}
4. 可能有帮助的前置习题
5. 所用到的数据结构与算法思想
- 秦九韶算法
6. 总结
秦九韶算法的应用,秦九韶算法还能够应用于进制转换,如 [AcWing] 2058. 笨拙的手指(C++实现)秦九韶算法