​LeetCode刷题实战415:字符串相加

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 字符串相加,我们先来看题面:

https://leetcode-cn.com/problems/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.

给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和并同样以字符串形式返回。

你不能使用任何內建的用于处理大整数的库(比如 BigInteger), 也不能直接将输入的字符串转换为整数形式。

示例

示例 1:
输入:num1 = "11", num2 = "123"
输出:"134"

示例 2:
输入:num1 = "456", num2 = "77"
输出:"533"

示例 3:
输入:num1 = "0", num2 = "0"
输出:"0"

解题

题目分析:

设置两个变量i,j分别从num1和num2的后面开始遍历,取对应位置的数字、前面计算所得进位相加的carry,carry对10的余数放入到结果中,carry/=10。因为两个字符串长度可能不同,要记得处理剩余的字符。最后记得carry可能不等于0,要对其进行处理 .

class Solution {
public:
    string addStrings(string num1, string num2) {
        int i=num1.size()-1,j=num2.size()-1,carry=0;
        string ans;
        while(i>=0&&j>=0){
            carry+=(num1[i]-'0')+(num2[j]-'0'); //从两个字符串的后面开始相加,记得加上进位
            ans.push_back(carry%10+'0'); //将本位的求和结果放到结果中
            carry/=10;
            --i;--j;
        }
        while(i>=0){ //和下面的while,这两个只会执行其中的一个
            carry+=(num1[i]-'0'); 
            ans.push_back(carry%10+'0');
            carry/=10;
            --i;
        }
        while(j>=0){
            carry+=(num2[j]-'0');
            ans.push_back(carry%10+'0');
            carry/=10;
            --j;
        }
        while(carry!=0){ //最后记得处理可能不为0的carry
            ans.push_back(carry%10+'0');
            carry/=10;
        }
        reverse(ans.begin(),ans.end()); //将结果字符串进行翻转
        return ans;
    }
};

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-400题汇总,希望对你有点帮助!

LeetCode刷题实战401:二进制手表

LeetCode刷题实战402:移掉 K 位数字

LeetCode刷题实战403:青蛙过河

LeetCode刷题实战404:左叶子之和

LeetCode刷题实战405:数字转换为十六进制数

LeetCode刷题实战406:根据身高重建队列

LeetCode刷题实战407:接雨水 II

LeetCode刷题实战408:有效单词缩写

LeetCode刷题实战409:最长回文串

LeetCode刷题实战410:分割数组的最大值

LeetCode刷题实战411:最短独占单词缩写

LeetCode刷题实战412:Fizz Buzz

LeetCode刷题实战413:等差数列划分

LeetCode刷题实战414:第三大的数

560fa52032f2bbc0ad91d454cf1c267c.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小猿666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值