LeetCode: Add Strings Solution

Add digits with carry

Approach

Let's take an example

1123 + 29
2
31 2 3
40 2 9
5-----
61 5 2
7
83 + 9 = 12, takes 2, carries 1
92 + 2 = 4, plus carry of 1, results in 5, takes 5
101 + 0 = 1, takes 1
11
12final result is 152

Implementation

1var addStrings = function (num1, num2) {
2 const maxLength = Math.max(num1.length, num2.length)
3 num1 = num1.padStart(maxLength, "0").split("").reverse()
4 num2 = num2.padStart(maxLength, "0").split("").reverse()
5
6 const res = []
7 let carry = 0
8
9 for (let i = 0; i < maxLength; i++) {
10 const digitSum = Number(num1[i]) + Number(num2[i]) + carry
11 res.push(digitSum % 10)
12 carry = Math.floor(digitSum / 10)
13 }
14
15 // in case we have carry leftover
16 carry && res.push(carry)
17
18 return res.reverse().join("")
19}

References

Original problem

String.prototype.padStart()

Comments

Loading comments...

Tags

leetcode

string

math

Next Post

LeetCode: Sort List

Yeah I skipped the follow-up

Previous Post

LeetCode: Multiply Strings

Will make this better. Word promised!

HoningJS

Search Posts