LeetCode刷题记2
1. 两数之和
来看一下题目:
我的解法:
class Solution {
public int reverse(int x) {
long res = 0;
while (x != 0) {
int tmp = x % 10;
res = res * 10 + tmp;
x /= 10;
}
if (res >= Math.pow(2, 31) || res < -Math.pow(2, 31)) {
res = 0;
}
return (int)res;
}
}
大佬的解法:
class Solution {
public int reverse(int x) {
int ans = 0;
while (x != 0) {
int pop = x % 10;
if (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && pop > 7))
return 0;
if (ans < Integer.MIN_VALUE / 10 || (ans == Integer.MIN_VALUE / 10 && pop < -8))
return 0;
ans = ans * 10 + pop;
x /= 10;
}
return ans;
}
}
作者:guanpengchn
链接:https://leetcode-cn.com/problems/reverse-integer/solution/hua-jie-suan-fa-7-zheng-shu-fan-zhuan-by-guanpengc/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
题目比较简单,大家思路一致,只是我比较菜,忘记了Integer.MAX_VALUE这个东西,mark一下~