415.字符串总和(javascript)415.AddStrings

原创
小哥 3年前 (2022-11-10) 阅读数 10 #大杂烩

给定两个字符串形式的非负整数 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()
};

leetcode : https://leetcode-cn.com/problems/add-strings/

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除