Your task is to create a function called addArrays, 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 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
(요약) 배열 요소를 하나로 합쳐서 더하고, 다시 배열로 펼쳐라. 결과값이 음수면 첫 요소에 -
추가.
function addArrays(array1, array2) { if(!array1.length && !array2.length) return []; if(!array1.length || !array2.length) return array1.length > array2.length ? array1 : array2; let num1 = parseInt(array1.join('')); let num2 = parseInt(array2.join('')); const result = num1 + num2; const sign = result > 0 ? 1 : -1; return `${Math.abs(result)}`.split('').map((char, idx) => idx ? char * 1 : char * sign); }
우선 배열에 요소가 없을 경우를 먼저 처리함.
그리고 각 요소를 모으고 합의 부호를 뽑아냄.
그런 후에 더한 결과값을split
하고, 첫 번째 요소에 부호를 곱하고return
.