(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;
    }   
};
相关推荐
众少成多积小致巨17 小时前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
clint4565 天前
C++进阶(1)——前景提要
c++
夜悊5 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴5 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0016 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾6 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you6 天前
constexpr函数
c++
凡人叶枫6 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫6 天前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss6 天前
BRpc使用
c++·rpc