Plus One

来源:互联网 发布:网络远程教育有学位吗 编辑:程序博客网 时间:2024/05/16 08:57

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.

not hard

recursion

class Solution:    # @param digits, a list of integer digits    # @return a list of integer digits    def plusOne(self, digits):        if len(digits)==0:            return []                return self.recur(digits, len(digits)-1, 1)        def recur(self, digits, step, carry):        if step==-1:            if carry==1:                digits = [1] + digits            return digits                digits[step] = digits[step] + carry        if digits[step] > 9:            digits[step] = digits[step] - 10            return self.recur(digits, step-1, 1)        else:            return self.recur(digits, step-1, 0);

iteration

class Solution:    # @param digits, a list of integer digits    # @return a list of integer digits    def plusOne(self, digits):        if len(digits)==0:            return []                carry = 1        for ind in range(len(digits)-1,-1,-1):            digits[ind] = digits[ind] + carry            if digits[ind]>9:                digits[ind] = digits[ind] - 10                carry = 1            else:                carry = 0                if carry==1:            digits = [1] + digits               return digits


Summary:

pay attention to the return when writing recursion code


0 0
原创粉丝点击