problem_solving_05.py 1.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
"""
加一
"""
from typing import List


class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        """
        加一
        :param digits:
        :return:
        """
        if not digits:
            return None
        s = ''
        res = []
        for value in digits:
            s = s + str(value)
        for i in str(int(s) + 1):
            res.append(int(i))
        return res

    def plusOne2(self, digits: List[int]) -> List[int]:
        """
        解法一的一行写法
        :param digits:
        :return:
        """
        return [int(i) for i in str(int(''.join([str(j) for j in digits])) + 1)]

    def plusOne3(self, digits: List[int]) -> List[int]:
        """
        常规解法
        :param digits:
        :return:
        """
        plus = 1
        for i in range(len(digits) - 1, -1, -1):
            if digits[i] + plus == 10:
                digits[i] = 0
                plus = 1
            else:
                digits[i] += plus
                plus = 0
        if plus == 1:
            digits.insert(0, 1)
        return digits


if __name__ == '__main__':
    result = Solution().plusOne3([1, 2, 3])
    print(result)