有符号的整数反转
直接从结果看:
- 取余(%)和取模在被除数与除数都同号的情况下没有区别。
- 在不同号时,取余得出的结果符号与被除数相同;取模得出的结果符号与除数相同。
从本质上看:
- a / b = c…d 而 d = a - b * c
- 取模操作求商c采用floor函数,向负无穷取整。
- 取余操作求商c采用fix函数,fix是向0取整的。
package leetcode.editor.cn;
//给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
//
// 示例 1:
//
// 输入: 123
//输出: 321
//
//
// 示例 2:
//
// 输入: -123
//输出: -321
//
//
// 示例 3:
//
// 输入: 120
//输出: 21
//
//
// 注意:
//
// 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
// Related Topics 数学
public class ReverseInteger{
public static void main(String[] args) {
Solution solution = new ReverseInteger().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int reverse(int x) {
int rev = 0;
while( x != 0)
{
int temp = x % 10;
x /= 10;
if(rev > Integer.MAX_VALUE / 10) return 0;
if(rev < Integer.MIN_VALUE / 10) return 0;
rev = rev * 10 + temp;
}
return rev;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}