LeetCode - 解題筆記 - 7 - Reverse Integer
Reverse Integer
Soluton 1
本題主體部分和進位加法的按位實現類似,但是額外的問題是本體需要額外判斷數字是否出現整型數溢位。因此需要在真的變成溢位數之前判斷這個數是否真的會溢位
- 時間複雜度: O ( n ) O(n) O(n), n n n為數字的位數
- 空間複雜度: O ( 1 ) O(1) O(1),因為只有固定個數個狀態變數需要維護
class Solution {
public:
int reverse(int x) {
int ans = 0;
// cout << INT_MIN << endl;
while (x != 0) {
int current = x % 10;
x /= 10;
// 有可能溢位,先檢查再真的相加
if ((ans > INT_MAX / 10) || (ans == INT_MAX / 10 && current > 7)) {
// cout << ans << " " << current << endl;
return 0;
}
if ((ans < INT_MIN / 10) || (ans == INT_MIN / 10 && current < -8)) {
// cout << ans << " " << current << endl;
return 0;
}
ans = ans * 10 + current;
}
return ans;
}
};
Solution 2
本問題的Python實現。本題的一個需要注意的點是a // b
的向下取整的特性,對正數不存在問題,但是對負數,向下取整意味著絕對值加1。Python的取餘實現為r = a - n * [a // n]
,因此對於負數需要額外考慮。因此在本題的情境中,對負數的取餘操作的除數應為-10
而非10
。
class Solution:
def reverse(self, x: int) -> int:
ans = 0
# print(13 // 10, 13 // -10)
while x != 0:
if x < 0:
current = x % -10
else:
current = x % 10
x = int(x / 10)
ans = int(ans * 10) + current
# print(x, current, ans)
# python 整型數不存在上下界
if ans >= 2**31 - 1 or ans <= -2 ** 31:
# print(-2 ** 31, ans)
return 0
return ans
相關文章
- Leetcode 7 Reverse IntegerLeetCode
- LeetCode - 解題筆記 - 12 - Integer to RomanLeetCode筆記
- LeetCode Reverse Integer(007)解法總結LeetCode
- 「每日一道演算法題」Reverse Integer演算法
- LeetCode - 解題筆記 - 8 - Palindrome NumberLeetCode筆記
- Reverse學習筆記筆記
- LeetCode 刷題筆記LeetCode筆記
- leetcode刷題筆記LeetCode筆記
- LeetCode - 解題筆記 - 10- Regular Expression MatchingLeetCode筆記Express
- leetcode刷題筆記605LeetCode筆記
- leetcode刷題筆記(3)(python)LeetCode筆記Python
- Leetcode 12 Integer to RomanLeetCode
- Leetcode 13 Roman to IntegerLeetCode
- leetcode 344. Reverse StringLeetCode
- Leetcode 151 Reverse Words in a StringLeetCode
- LeetCode刷題筆記9.2-9.9LeetCode筆記
- leetcode刷題筆記8.5-8.9LeetCode筆記
- Leetcode刷題筆記8.12-8.16LeetCode筆記
- Leetcode 12. Integer to RomanLeetCode
- Leetcode 273 Integer to English WordsLeetCode
- Leetcode 8 String to Integer (atoi)LeetCode
- 題解筆記筆記
- Leetcode 206. Reverse Linked ListLeetCode
- Integer類小細節隨筆記錄筆記
- CF1458D Flip and Reverse 題解
- LeetCode - Easy - 206. Reverse Linked ListLeetCode
- Leetcode 25 Reverse Nodes in k-GroupLeetCode
- Leetcode171-190刷題筆記(非困難題)LeetCode筆記
- Leetcode 記錄 不會解的題LeetCode
- LeetCode解題記錄(雙指標專題)LeetCode指標
- LeetCode Integer to Roman(012)解法總結LeetCode
- LeetCode Roman to Integer(013)解法總結LeetCode
- [leetcode] 1394. Find Lucky Integer in an ArrayLeetCode
- 【Leetcode】25.Reverse Nodes in k-GroupLeetCode
- LeetCode刷題記錄與題解(C++版本)LeetCodeC++
- leetCode解題記錄1 - 兩數之和LeetCode
- 刷題記錄:劍指offer+遇到的筆試題+LeetCode筆試LeetCode
- LeetCode String to Integer (atoi)(008)解法總結LeetCode