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 Integer)LeetCode
- Leetcode 7 Reverse IntegerLeetCode
- leetcode Reverse IntegerLeetCode
- LeetCode - 解題筆記 - 12 - Integer to RomanLeetCode筆記
- Reverse Integer leetcode javaLeetCodeJava
- 【LeetCode從零單排】No.7 Reverse IntegerLeetCode
- Leetcode-Problem:Reverse IntegerLeetCode
- [LeetCode] Reverse Integer 翻轉整數LeetCode
- LeetCode Reverse Integer(007)解法總結LeetCode
- 「每日一道演算法題」Reverse Integer演算法
- leetcode刷題--Reverse BitsLeetCode
- Reverse學習筆記筆記
- LeetCode 第 343 題 (Integer Break)LeetCode
- LeetCode - 解題筆記 - 8 - Palindrome NumberLeetCode筆記
- LeetCode 第 190 題 (Reverse Bits)LeetCode
- leetcode刷題--Reverse Linked ListLeetCode
- LeetCode 刷題筆記LeetCode筆記
- leetcode刷題筆記LeetCode筆記
- leetcode刷題筆記605LeetCode筆記
- LeetCode - 解題筆記 - 10- Regular Expression MatchingLeetCode筆記Express
- Leetcode Integer to RomanLeetCode
- leetcode Roman to IntegerLeetCode
- [LeetCode] Roman to IntegerLeetCode
- 題解筆記筆記
- LeetCode-Reverse BitsLeetCode
- Integer類小細節隨筆記錄筆記
- Leetcode 12 Integer to RomanLeetCode
- Leetcode 13 Roman to IntegerLeetCode
- LeetCode-Integer ReplacementLeetCode
- LeetCode-Integer BreaksLeetCode
- Leetcode-Roman to IntegerLeetCode
- Leetcode-Integer to RomanLeetCode
- Integer to Roman leetcode javaLeetCodeJava
- Roman to Integer leetcode javaLeetCodeJava
- Leetcode Reverse Words in a StringLeetCode
- Leetcode Evaluate Reverse Polish NotationLeetCode
- leetcode Reverse Words in a StringLeetCode
- leetcode刷題筆記(3)(python)LeetCode筆記Python