66. Plus One
題目網址:https://leetcode.cn/problems/plus-one/
題意:給一整數 array
digits
用來表示一非負整數。返回該非負整數 + 1 後所表示的digits
。非負整數的最高為儲存在
digits
的首位, 其中digits[i]
只儲存單個數字。除了
0
之外, 其他整數都不會以0
作為開頭。
Solution 1:
想法:遍歷
digits
, 並紀錄進位carry
。若最後carry
為1
, 則在digits
最前面補上1
cpp
class Solution { |
- time:
➔ for loop - space:
➔ 只需常數空間
Solution 2:
想法:改進 Solution 1, 改成一旦不用進位, 則終止循環(循環裡會不斷將
digits[i] + 1
), 並返回 digits
digits[i] < 9
:代表不用進位, 將digits[i] + 1
後, 終止循環並返回digits
digits[i] == 9
:代表要進位, 將digits[i]
設為0
, 並繼續循環
cpp
class Solution { |
- time:
➔ for loop - space:
➔ 只需常數空間
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Zako's Blog!
評論