题目:整数反转
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
复制代码
示例:
输入: 123
输出: 321
输入: -123
输出: -321
输入: 120
输出: 21
复制代码
思考:
这道题整数反转的可以参考之前那篇回文数的方法。
将x对10 求余,然后在除以10,再将结果对10求余,再次除以10。一直到结果为0为止。
接着将每次求得的余数按位数相加,得到的结果就是将原来的x翻转过来的数。
例如:12345
12321 对10求余:余数为5 除以10:结果为1234
1232 对10求余:余数为4 除以10:结果为123
123 对10求余:余数为3 除以10:结果为12
12 对10求余:余数为2 除以10:结果为1
1 对10求余:余数为1 除以10:结果为0
至此为止,我们发现将余数加起来就是54321,就是将原数12345翻转后的结果。
复制代码
注意:要判断反转后的数是否会超过32位整形最大最小值!
public final class Integer extends Number implements Comparable<Integer> {
/**
* A constant holding the minimum value an {@code int} can
* have, -2<sup>31</sup>.
*/
@Native public static final int MIN_VALUE = 0x80000000;//十进制为-2147483648
/**
* A constant holding the maximum value an {@code int} can
* have, 2<sup>31</sup>-1.
*/
@Native public static final int MAX_VALUE = 0x7fffffff;//十进制为2147483647-1
复制代码
实现:
class Solution {
public int reverse(int x) {
int result = 0;
while (x != 0) {
int remainder = x % 10;
x /= 10;
//乘以10后时候会大于Integer.MAX_VALUE,所以乘之前先和Integer.MAX_VALUE比较
//如果相等最后一位余数不能大于7
if (result > Integer.MAX_VALUE/10 || (result == Integer.MAX_VALUE / 10 && remainder > 7))
return 0;
//乘以10后时候会小于Integer.MIN_VALUE,所以乘之前先和Integer.MIN_VALUE比较
//如果相等最后一位余数不能小于-8
if (result < Integer.MIN_VALUE/10 || (result == Integer.MIN_VALUE / 10 && remainder < -8))
return 0;
result = result * 10 + remainder ;
}
return result;
}
}
复制代码