(C++)字符串相加

愿所有美好如期而遇


题目链接:415. 字符串相加 - 力扣(LeetCode)

思路

我们看到字符串长度可能到达一万,而且不允许使用处理大整数的库,也就是说,转成整数相加后再转成字符串是不可行的。

那么我们就让字符串尾部的字符各自减去48后单位相加,再加进位,然后得到一个大小,求余后+48尾插到一个我们定义的字符串中,进位除以10,然后不为空的字符串删除尾部的单个字符,这就是单趟。

我们用循环来走,直到两个字符串都为空。

图解

代码

复制代码
class Solution {
public:
    string addStrings(string num1, string num2) 
    {
        string result;
        int next = 0;

        char tmp1 = 0;
        char tmp2 = 0;

        while(!num1.empty() || !num2.empty())
        {
            if(!num1.empty())
                tmp1 = num1[num1.size()-1] - 48;
            else
                tmp1 = 0;

            if(!num2.empty())
                tmp2 = num2[num2.size()-1] - 48;
            else
                tmp2 = 0;

            int sum = tmp1 + tmp2 + next;
            next = sum / 10;
            sum %= 10;

            result += (sum+48);

            if(!num1.empty())
                num1.erase(num1.end()-1);
            if(!num2.empty())
                num2.erase(num2.end()-1);
        }

        if(next > 0)
            result += '1';

        reverse(result.begin(),result.end());
        return result;
    }   
};
相关推荐
终焉代码2 分钟前
【Linux】进程初阶(1)——基本进程理解
linux·运维·服务器·c++·学习·1024程序员节
我想吃余2 分钟前
Linux进程间通信:管道与System V IPC的全解析
linux·服务器·c++
紫荆鱼3 分钟前
设计模式-备忘录模式(Memento)
c++·后端·设计模式·备忘录模式
Wind哥13 分钟前
VS Code搭建C/C++开发调试环境-Windows
c语言·开发语言·c++·visual studio code
Skrrapper1 小时前
【C++】C++ 中的 map
开发语言·c++
m0_748233642 小时前
【C++list】底层结构、迭代器核心原理与常用接口实现全解析
c++·windows·list
qq_310658512 小时前
webrtc代码走读(八)-QOS-FEC-flexfec rfc8627
网络·c++·webrtc
惊讶的猫3 小时前
c++基础
开发语言·c++
Code_Shark8 小时前
AtCoder Beginner Contest 426 题解
数据结构·c++·算法·数学建模·青少年编程
仰泳的熊猫8 小时前
LeetCode:698. 划分为k个相等的子集
数据结构·c++·算法·leetcode