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