Source: https://www.interviewbit.com/problems/add-one-to-number/

Given a non-negative number represented as an array of digits, add 1 to the number ( increment the number represented by the digits ).

The digits are stored such that the most significant digit is at the head of the list.

Example:

If the vector has [1, 2, 3]

the returned vector should be [1, 2, 4]

as 123 + 1 = 124.

這題對於輸入端的正整數排列形式沒有任何限制,也就是說list開頭可為0, for example, [0, 0, 1, 2, 3];但對於輸出端則有限制必須為正整數形式,就前述例子,輸出應為124而非00124


解題思路:

  1. 對輸入端的前置0及極端狀況執行預處理;
  2. 對list的最末項+1;
  3. 確認+1後是否受十進位影響,用loop方式執行確認及調整;
  4. 完成後合併各項並輸出。

Code:

def plusOne(A):
    if len(A) == 0: return [1]
    num = A
    while len(num) > 0 and num[0] == 0:
        num.remove(0)
    digits = len(num)
    if digits == 0: return [1]
    i = -1
    num[i] = num[i] + 1
    while num[i] % 10 == 0 and i + digits > 0:
        num[i] = 0
        num[i-1] += 1
        i -= 1
    if num[0] % 10 == 0:
        num[0] = 0
        num = [1] + num

    return num

GitHub: Add One To Number

 

發表留言