minimanimoh / Udacity_DS-A

0 stars 0 forks source link

DS&A - 2. Data Structures - Lesson 1. Add One #3

Open minimanimoh opened 3 years ago

minimanimoh commented 3 years ago

You are given a non-negative number in the form of list elements. For example, the number 123 would be provided as arr = [1, 2, 3]. Add one to the number and return the output in the form of a new list.

Example 1:

input = [1, 2, 3] output = [1, 2, 4] Example 2:

input = [9, 9, 9] output = [1, 0, 0, 0] Challenge:

One way to solve this problem is to convert the input array into a number and then add one to it. For example, if we have input = [1, 2, 3], you could solve this problem by creating the number 123 and then separating the digits of the output number 124.

But can you solve it in some other way?

def add_one(arr): output = 1

for i in range(len(arr), 0, -1):
    output = output + arr[i - 1]
    borrow = output // 10

    if borrow == 0:
        arr[i - 1] = output
        break
    else:
        arr[i - 1] = output % 10
        output = borrow

    arr = [borrow] + arr
    index = 0

    while arr[index] == 0:
        index += 1

    return arr[index:]
minimanimoh commented 3 years ago

- Question What makes range(len(arr)) to add 0, -1? it works without adding them. - Note v As units are the key, no need to change all arrays to integer or float. When units >= 10, the code should consider (+) biggest digit by using the index. v output // 10 is used to reflect the biggest digit and output % 10 is used to reflect the unit digit.