https://leetcode.com/problems/reverse-integer/description/
題目大意:給一個整數,返回其每位倒序的整數。
解題思路:初始old = 0,每次取整數n的最低位tail,然後從低向高構建新整數new = old * 10 + tail。取得tail後,去掉n的最低位,n=n/10,進入下一輪,直到n=0。
注意為了避免溢出,每次記錄old和new,然後用相反的方法:old = (new-tail)/ 10,判斷old和new是否相等,若前後不相等,說明溢出。
代碼:
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; x /= 10; result = newResult; } return result; }};
python實現:基本上與c語言相同,不同在於負數模數和除法需要特別處理,在此簡化為先用正數處理,再轉為負數。此外還需注意判斷是否溢出,因為python的整數類型範圍似乎比c語言要大,因此不用上面的做法判斷溢出,直接檢驗是否在[-2^31, 2^31-1]即可
class Solution: def reverse(self, x): """ :type x: int :rtype: int """ result = 0 while x != 0: if x > 0: tail = x % 10 else: tail = -(-x % 10) #考慮負數處理 newResult = result * 10 + tail if x > 0: x //= 10 else: x = -(-x // 10) #考慮負數處理 result = newResult if result < 2**31-1 and result > -2**31: return result else: return 0