问题陈述

Problem Statement:

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?

python实现

1
2
3
4
5
6
7
8
9
10
11
12
13
def add_one(input_list):
if input_list is None:
return None
i = len(input_list) - 1
while i >= 0:
if input_list[i] != 9:
input_list[i] += 1
return input_list
elif input_list[i] == 9:
input_list[i] = 0
i -= 1
input_list.insert(0, 1)
return input_list

测试用例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def test_function(test_case):
arr = test_case[0]
solution = test_case[1]

output = add_one(arr)
for index, element in enumerate(output):
if element != solution[index]:
print("Fail")
return
print("Pass")

arr = [0]
solution = [1]
test_case = [arr, solution]
test_function(test_case)

arr = [1, 2, 3]
solution = [1, 2, 4]
test_case = [arr, solution]
test_function(test_case)

arr = [9, 9, 9]
solution = [1, 0, 0, 0]
test_case = [arr, solution]
test_function(test_case)