索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode
007.Reverse_Integer (Easy)
链接:
题目:https://oj.leetcode.com/problems/Reverse-Integer/
代码(github):https://github.com/illuz/leetcode
题意:
反转一个数。
分析:
注意读入和返回的数都是 int 型的,这时就要考虑反转后这个数会不会超 int,超的话就返回 0 。这时处理数时最好用比 int 大的类型,不然恐怕会超范围。
当然也可以用 int :if (result > (INT_MAX/10))
还有一点就是还要考虑前导零。
代码:
C++:class Solution {
public:
int reverse(int x) {
long long tmp = abs((long long)x);
long long ret = 0;
while (tmp) {
ret = ret * 10 + tmp % 10;
if (ret > INT_MAX)
return 0;
tmp /= 10;
}
if (x > 0)
return (int)ret;
else
return (int)-ret;
}
};
Java:
public class Solution {
public int reverse(int x) {
int ret = 0;
while (Math.abs(x) != 0) {
if (Math.abs(ret) > Integer.MAX_VALUE)
return 0;
ret = ret * 10 + x % 10;
x /= 10;
}
return ret;
}
}
Python:
class Solution:
# @return an integer
def reverse(self, x):
revx = int(str(abs(x))[::-1])
if revx > math.pow(2, 31):
return 0
else:
return revx * cmp(x, 0)