给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和并同样以字符串形式返回。
你不能使用任何內建的用于处理大整数的库(比如 BigInteger), 也不能直接将输入的字符串转换为整数形式。
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.
示例 1:
输入:num1 = "11", num2 = "123"
输出:"134"
示例 2:
输入:num1 = "456", num2 = "77"
输出:"533"
示例 3:
输入:num1 = "0", num2 = "0"
输出:"0"
提示:
1 <= num1.length, num2.length <= 104
num1 和num2 都只包含数字 0-9
num1 和num2 都不包含任何前导零
我们定义两个指针 i 和 j分别指向num1和 num2的末尾,即最低位,同时定义一个变量add 维护当前是否有进位,然后从末尾到开头逐位相加即可。你可能会想两个数字位数不同怎么处理,这里我们统一在指针当前下标处于负数的时候返回 0,等价于对位数较短的数字进行了补零操作,这样就可以除去两个数字位数不同情况的处理
var addStrings = function (num1, num2) {
let len1 = num1.length - 1
let len2 = num2.length - 1
let add = 0
let newList = []
//某个字符串还没循环完,或者还存在进位时,循环继续
while (len1 >= 0 || len2 >= 0 || add != 0) {
//当某个字符串索引小于0时,用0补位,当前位得到的值为两两相加再加进位值
let current = (len1 >= 0 ? num1[len1] - '0' : 0) + (len2 >= 0 ? num2[len2] - '0' : 0) + add
add = current >= 10 ? Math.floor((current) / 10) : 0//获得进位值,十进制,满十进一
current = current >= 10 ? (current) % 10 : current//余数为最终保留的数字,然后将其存在列表中
newList.push(current)
len1--
len2--
}
//因为是从后往前遍历,所以,列表需要翻转,再通过[].join('')得到最终字符串
return newList.reverse().join('')
};