Try it here
Subscribe
Interview Experience

Google 9+ Years experience Customer Solution Engineer

google_9+_years_experience_customer_solution_engineer

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]

Solutions:

Approach 1:

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)

Approach 2:

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)

Approach 3:

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)

Approach 4:

arr = [9, 9, 9, 9]
astr = ''.join(map(str,arr))
res = list(str(int(astr) + 1))
res = list(map(int,res))
print(list(res))

Writer profile pic

Prithvi on Feb 15, 2022 at 08:01 am


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.



Post Comment

Comments( 0)

×

Forgot Password

Please enter your email address below and we will send you information to change your password.