Add Strings
Description
Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
Solution(javascript)
/**
* @param {string} num1
* @param {string} num2
* @return {string}
*/
var addStrings = (num1, num2) => {
const reversedNum1 = num1.split('').reverse()
const reversedNum2 = num2.split('').reverse()
const { shorter, longer } = reversedNum1.length < reversedNum2.length
? { shorter: reversedNum1, longer: reversedNum2 }
: { shorter: reversedNum2, longer: reversedNum1 }
let rem = 0
let result = longer.reduce((acc, digit1, index) => {
const total = parseInt(digit1, 10) + (parseInt(shorter[index], 10) || 0) + rem
if (total >= 10) {
rem = 1
} else {
rem = 0
}
return [
...acc,
total >= 10 ? total - 10 : total,
]
}, [])
result = rem === 1 ? [...result, rem] : result
return result.reverse().join('')
}