LeetCode-415. Add Strings

问题描述

Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.

You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

Example :

1
2
Input: num1 = "11", num2 = "123"
Output: "134"

Constraints:

  • 1 <= num1.length, num2.length <= 104
  • num1 and num2 consist of only digits.
  • num1 and num2 don’t have any leading zeros except for the zero itself.

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*
* @Description: 415. Add Strings
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* @param {string} num1
* @param {string} num2
* @return {string}
*/
const addStrings = function (num1, num2) {
let i = num1.length - 1
let j = num2.length - 1
let carry = 0
let res = ''
while (i >= 0 || j >= 0 || carry !== 0) {
let x = (i >= 0) ? (+num1.charAt(i)) : 0
let y = (j >= 0) ? (+num2.charAt(j)) : 0
let sum = x + y + carry
res = sum % 10 + res
carry = Math.floor(sum / 10)
i--
j--
}
return res
}

console.log(addStrings('2111', '123'))