LeetCode第七題 顛倒整數
給定一個範圍爲 32 位 int 的整數,將其顛倒。
例 1:
輸入: 123
輸出: 321例 2:
輸入: -123
輸出: -321例 3:
輸入: 120
輸出: 21
java
public int reverse(int x) {
int result = 0;
while (x != 0) {
int tail = x % 10;
int newResult = result * 10 + tail;
if ((newResult - tail) / 10 != result)
return 0;
result = result * 10 + tail;
x = x / 10;
}
return result;
}
C++
class Solution
{
public:
int reverse(int x)
{
int result = 0;
while(x!=0)
{
int tail = x%10;
int newResult = result*10 + tail;
if((newResult-tail)/10!=result)return 0;
result = newResult;
x = x/10;
}
return result;
}
};
使用python時,有個別測試用例無法通過,跟題目中 “範圍爲32位的int整數”有關,以後可以再研究一下。
python
class Solution(object):
def reverse(self, x):
result = 0
if (x < 0):
return -Solution().reverse(-x)
while (x != 0):
tail = x % 10
newResult = result * 10 + tail
if ((int(newResult - tail) / 10) != result):
return 0
result = newResult
x = int(x / 10)
return result