415. 字符串相加(javascript)415. Add Strings

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值