You are given two non-empty linked lists representing two non-negative integers.
The digits are stored in reverse order, and each of their nodes contains a single digit.
Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Input: l1 = [0], l2 = [0]
Output: [0]
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
Math.pow(10, 인덱스)
로 자리수만큼 곱하고 > 각 수를 더한 후에 > 문자열로 잘라서 반환
reduce
를 쓰려고 했다
const reducer = (accumulator, currentValue, currentIndex) => accumulator + (currentValue * Math.pow(10, currentIndex))
1e+30
처럼 처리가 되고 이걸 문자열로 자르면 10030
가 됐다.var addTwoNumbers = function(l1, l2) {
let totalValue = ""
let checkNode = l1
let carry = 0
while(checkNode) {
const l1Val = checkNode?.['val'] ? checkNode?.['val'] : 0
const l2Val = l2?.['val'] ? l2['val'] : 0
// 둘이 합쳐서 최대는 18
const total = l1Val + l2Val + (carry > 0? carry : 0)
const remain = total % 10
carry = (total / 10) >> 0
totalValue += remain
checkNode = checkNode['next']
if(! checkNode && l2){
checkNode = l2['next']
l2 = null
continue;
}
l2 = l2?.['next'] ? l2['next'] : null
}
if(carry > 0) {
totalValue += carry
}
let totalValueIdx = totalValue.length -1
let answer = null; // null로 안해두면 undefined가 들어가서 잘못된 답이라는 에러 발생
while (totalValueIdx >= 0){
answer = {
val: ~~totalValue[totalValueIdx--],
next: answer
}
}
return answer
};