LeetCode: Add Strings Solution
Add digits with carryApproach
Let's take an example
1123 + 29231 2 340 2 95-----61 5 2783 + 9 = 12, takes 2, carries 192 + 2 = 4, plus carry of 1, results in 5, takes 5101 + 0 = 1, takes 11112final 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()56 const res = []7 let carry = 089 for (let i = 0; i < maxLength; i++) {10 const digitSum = Number(num1[i]) + Number(num2[i]) + carry11 res.push(digitSum % 10)12 carry = Math.floor(digitSum / 10)13 }1415 // in case we have carry leftover16 carry && res.push(carry)1718 return res.reverse().join("")19}
References
Comments
Loading comments...
Tags
leetcode
string
math
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Sort List
Yeah I skipped the follow-up
Previous Post
LeetCode: Multiply Strings
Will make this better. Word promised!