Crack LeetCode 之 7. Reverse Integer
阿新 • • 發佈:2018-12-16
https://leetcode.com/problems/reverse-integer/
這一題很簡單,需要注意檢查越界的程式碼。以下是C++和python的實現。
struct Solution {
int reverse(int x) {
long long sum = 0;
for (; x; x = x / 10) {
sum = sum * 10 + x % 10;
if (sum > INT_MAX || sum < INT_MIN)
return 0;
}
return sum;
}
};
class Solution: def reverse(self, x): num = abs(x) sum = 0 while num != 0: sum = sum * 10 + num % 10; num = int(num/10); if sum > (2**31-1) or sum < (-2**31): return 0 if x > 0: return sum return -sum