title :
Given a non-negative number represented as an array of digits, plus one to the number.
The digits is stored such, the most significant digit was at the head of the list.
code : OJ Test via runtime:47 ms
1 classSolution:2 #@param digits, a list of integer digits3 #@return A list of integer digits4 defPlusOne (self, digits):5 ifDigits isNone:6 returnNone7 ifLen (digits) = =0:8 returndigits9Length =len (digits)TenNew_last_digit = digits[length-1] + 1 One ifNEW_LAST_DIGIT/10 = =0: ADIGITS[LENGTH-1] =New_last_digit - returndigits - Else: theJinwei = 1 -DIGITS[LENGTH-1] =0 - forIinchRange (length-2,-1,-1): -Curr_value = Jinwei +Digits[i] + ifCURR_VALUE/10 = =0: -Digits[i] =Curr_value + returndigits A Else: atDigits[i] = curr_value% 10 -Digits.insert (0,1) - returnDigits
Ideas :
Exclude special Case First
And then gradually go ahead and maintain a Jinwei variable
Note that if the final carry needs to be added to the beginning of the array at the start of a 1 it is not known that the Python array has this function before the Insert function is used
Leetcode "Plus One" Python implementation