【LeetCode with Python】 Plus One

博客域名: http://www.xnerv.wang
原题页面: https://oj.leetcode.com/problems/plus-one/
题目类型:模拟数值运算
难度评价:★
本文地址: http://blog.csdn.net/nerv3x3/article/details/37336603

Given a non-negative number represented as an array of digits, plus one to the number.

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


用一个int数组代表一个数值,最左边是最高位,现要求加上1,同样地返回一个int数组代表计算结果。
非常简单的模拟加法,注意进位问题,如果是99,999这种,最后加上1后还要在数组最左边插入一个元素1。
空间复杂度O(1)。时间复杂度O(N)。


class Solution:
    # @param digits, a list of integer digits
    # @return a list of integer digits
    def plusOne(self, digits):
        len_s = len(digits)
        carry = 1
        for i in range(len_s - 1, -1, -1):
            total = digits[i] + carry
            digit = int(total % 10)
            carry = int(total / 10)
            digits[i] = digit
        if 1 == carry:
            digits.insert(0, 1)
        return digits

你可能感兴趣的:(LeetCode,with,Python,LeetCode,with,Python)