LeetCode-7. Reverse Integer(Easy):
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
我的解法:
由于是一道简单题,普通解法就可以了,很容易。看到一个速度最快的java代码,学习一下其中的用法。注意一下,题目中显示的范围[-231,231-1]是指2的31次方,刚好java中整数类Integer自带整数的最大最小值表示
Integer.MAX_VALUE=2 的 31 次方 - 1 = 2147483648 - 1 = 2147483647
Integer.MIN_VALUE=Integer.MAX_VALUE + 1 = Integer.MIN_VALUE = -2147483648
最大值整除10之后余7
最小值整除10之后余-8
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
}