물음표 살인마의 개발블로그

알고리즘 문제/CodeWar

Sum two arrays

BEstyle 2022. 11. 18. 14:28

DESCRIPTION:

Your task is to create a function called sum_arrays(), which takes two arrays consisting of integers, and returns the sum of those two arrays.

The twist is that (for example) [3,2,9] does not equal 3 + 2 + 9, it would equal '3' + '2' + '9' converted to an integer for this kata, meaning it would equal 329. The output should be an array of the sum in a similar fashion to the input (for example, if the sum is 341, you would return [3,4,1]). Examples are given below of what two arrays should return.

[3,2,9],[1,2] --> [3,4,1]
[4,7,3],[1,2,3] --> [5,9,6]
[1],[5,7,6] --> [5,7,7]

If both arrays are empty, return an empty array.

In some cases, there will be an array containing a negative number as the first index in the array. In this case treat the whole number as a negative number. See below:

[3,2,6,6],[-7,2,2,8] --> [-3,9,6,2] # 3266 + (-7228) = -3962

def sum_arrays(array1,array2):
    num1=""
    num2=""
    if array1==[] and array2==[]:
        return []
    if array1!=[]:
        for i in array1:
            num1+=str(i)
        num1=int(num1)
    else:
        num1=0
    if array2!=[]:
        for i in array2:
            num2+=str(i)
        num2=int(num2)
    else:
        num2=0
    ans=[]
    if (num1+num2)>=0:
        for i in str(num1+num2):
            ans.append(int(i))
    else:
        for i in str(num1+num2)[1:]:
            ans.append(int(i))
        ans[0]=ans[0]*-1
    return ans

'알고리즘 문제 > CodeWar' 카테고리의 다른 글

Range Extraction  (0) 2022.11.18
Sort Arrays(Ignoring case)  (0) 2022.11.18
Triangle Number Check  (0) 2022.11.18
Pascal's Triangle #2  (0) 2022.11.17
Design a simple automation  (0) 2022.11.17