Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Example 2:
Related Topics: Array
這題也是逐位相加的的題目,不同的是這題加數固定是 1,所以要考慮的情況會簡單很多。關於這題我想到兩種做法,在 LeetCode 上跑起來效能差不多。
第一種想法是將加數當做進位數 carry ,使用迴圈依序取值與進位數相加,若相加結果大於 10 則繼續進位。最後回傳時,若進位數仍大於 1 ,則將其插入陣列前方。
迴圈執行中,我多加了一個終止條件,一旦進位值為 0 就停止迴圈,因為進位值若為 0 ,表示下個位數的值會與 0 相加,值不變也不會產生進位數,因此可以直接終止迴圈,減少迴圈次數。
另一個想法則是,判斷尾數是否為 9 ,因為在加數為 1 情況下,唯一會啟動進位情況只有 (9,1) 這種組合。因此遇到 9 就回填 0 ,直到遇到第一個非 9 的數字,將其加 1 後中斷迴圈。回傳時,需檢查最高位是否為 0,若為 0 則在前方補上一個 1。
相同想法的另一個實作,但好像也沒比較快,三個程式碼都落在 56ms~60ms 左右。
本文作者: 辛西亞.Cynthia
本文連結: 辛西亞的技能樹 / hackmd 版本
版權聲明: 部落格中所有文章,均採用 姓名標示-非商業性-相同方式分享 4.0 國際 (CC BY-NC-SA 4.0) 許可協議。轉載請標明作者、連結與出處!