Write a function that accepts a number encoded as an array of digits, e.g. [1,9,3,8] for the number 1938, and returns the encoded number incremented by 1, e.g. returns [1,9,3,9].
Examples: [1,9,3,8] -> [1,9,3,9] [4,4,4] -> [4,4,5] [4]-> [5] [9] -> [1,0]
arr = [1,9,3,8] c = 0 if arr[-1] == 9: arr[-1] = 0 c = 1 else: arr[-1] = arr[-1] + 1 for i in range(len(arr) - 2, -1, -1): if c > 0: arr[i] = 0 if arr[i] + c > 9 else arr[i] + c c = 1 if arr[i] == 0 else 0 if c > 0: arr.insert(0, c) print(arr)
arr = [9, 9, 9, 9] arr.reverse() c = 0 arr[0] = arr[0] + 1 for i in range(len(arr)): if c > 0: arr[i] += c c = arr[i]//10 if c!= 0: arr[i] = arr[i]%10 if c > 0: arr.append(c) arr.reverse() print(arr)
arr = [9, 9, 9, 8] l = len(arr) - 1 while l >= 0 and arr[l] == 9: arr[l] = 0 l -= 1 if l < 0: arr.insert(0, 1) else: arr[l] += 1 print(arr)
arr = [9, 9, 9, 9] astr = ''.join(map(str,arr)) res = list(str(int(astr) + 1)) res = list(map(int,res)) print(list(res))
This article is contributed by Prithvi. If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.