1 つ追加します (Letches | 基本アルゴリズム | 配列 | Python)

1. トピックの説明

ここに画像の説明を挿入

2、コード分析

解決策 1: 文字列と整数の間で相互に変換する

class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """

        result = []
        string = ''
        for i in digits:
            string = string+str(i)
        string = str(int(string)+1)
        for i in string:
            result.append(int(i))
        return result

# solution = Solution()
# result = solution.plusOne([9,9])
# print(result)

この解決策には特別なトリックはなく、文字列と整数の間で相互に変換するだけです。

解決策 2: 最長のサフィックス 9 を見つける

class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        length = len(digits)
        for i in range(length-1,-1,-1):
            if(digits[i]==9):
                digits[i]=0
            else:
                digits[i]+=1
                break
        if(digits[0]==0):
            # digits.insert(0,1) # 在0的位置插入1
            digits = [1]+[0]*length
        return digits

# solution = Solution()
# result = solution.plusOne([2,3,4])
# print(result)

配列に 1 を追加する場合、次の 3 つの状況が考えられます。

ここに画像の説明を挿入

3. まとめ

公式ソリューションへのリンクはここにあります一般に、この質問は観察ルールの質問としてカウントされる必要があります。

おすすめ

転載: blog.csdn.net/qq_40968179/article/details/128519240