#66. Plus One

https://leetcode.com/problems/plus-one/#/description

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.

翻譯

  • 給定一個(gè)代表非負(fù)整數(shù)的列表,其中每一個(gè)值代表該位的數(shù)值。
  • 對(duì)該整數(shù)+1,返回新的列表
  • 比如 19=[1,9] 19+1=20=[2, 0]

分析

  • 設(shè)置進(jìn)位符 carry=0
  • 逆序遍歷列表
  • 所有元素均+carry list[i] += carry
  • 若list[i]+carry = 10,則list[i] = 0, carry = 1; 否則carry = 0
  • 若遍歷結(jié)束時(shí),carry == 1,則需要新加入一個(gè)[1],放入列表最前面,即
  • [9] ->[1, 0]
# Time O(n)
class Solution(object):
    def plusOne(self, digits):
        carry = 0
        for i in range(len(digits)-1, -1, -1):
            digits[i] += carry
            if i == len(digits) - 1:
                digits[i] += 1
            if digits[i] == 10:
                digits[i] = 0
                carry = 1 # 進(jìn)位標(biāo)志
            else:
                carry = 0
        if carry == 1:
            digits.insert(0, 1)
        return digits 
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容