Add One to Array

One 1 to an array. Test your program.

class Solution:
    def plusOne(self, array):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        if not array: return array

        for i, num in enumerate(reversed(array)):
            i = len(array) - i - 1
            if num != 9:
                array[i] += 1
                return array
            else:
                array[i] = 0
        array.insert(0, 1)
        return array


# sanity test
t1 = [0]
t2 = [1, 0]
t3 = [0, 1]
t4 = [9]
t5 = [9, 9]
t6 = [7, 8]
t7 = [7, 9]

obj = Solution()
print(obj.plusOne(t1))
print(obj.plusOne(t2))
print(obj.plusOne(t3))
print(obj.plusOne(t4))
print(obj.plusOne(t5))
print(obj.plusOne(t6))
print(obj.plusOne(t7))


from random import randint
import copy


# real test
def test_add_one_array():
    for i in range(0, 10000):
        # generate 0 - 10 random numbers
        list_len = randint(1, 10)
        the_list = []
        for i in range(0, list_len):
            the_list.append(randint(0, 9))

        original_list = copy.deepcopy(the_list)
        the_list = obj.plusOne(the_list)
        real_result = int(''.join(str(i) for i in original_list)) + 1
        assert(int(''.join(str(i) for i in the_list)) == real_result)


test_add_one_array()

Last updated