I am practicing interview questions and have written the following code for the given task.
Task : Given a non-negative number represented as an array of digits, add 1 to the number (increment the number represented by the digits). The digits are stored such that the most significant digit is at the head.
Code:
class Solution:
# @param A : list of integers
# @return a list of integers
def plusOne(self, A):
Rev_A = A[::-1]
i = 0
while i <= len(A)-1:
if Rev_A[i] != 9:
Rev_A[i] +=1
carry = 0
break
else:
Rev_A[i] = 0
carry = 1
i += 1
if carry == 1:
Rev_A.append(1)
while True:
if Rev_A[-1]==0:
Rev_A.pop()
else:
break
return Rev_A[::-1]
def __init__(self):
self.list = []
Test cases:
if __name__ == "__main__":
A = Solution()
## Test Cases
print A.plusOne([0])
print A.plusOne([9,0,0])
print A.plusOne([6,9,9])
print A.plusOne([9,9,9])
print A.plusOne([0,9,9,9])
print A.plusOne([0,0,0,1,2,3])
How can this code be better?