[LeetCode]415. Add Strings

来源:互联网 发布:手机淘宝店铺链接在哪 编辑:程序博客网 时间:2024/06/02 06:15

[LeetCode]415. Add Strings

题目描述

这里写图片描述

思路

水题,遍历字符串,按位相加即可

代码

#include <iostream>#include <string>using namespace std;class Solution {public:    string addStrings(string num1, string num2) {        string res;        int temp1, temp2, carry = 0;        for (int i = num1.size() - 1, j = num2.size() - 1; ; --i, --j) {            if (i < 0 && j < 0)                break;            temp1 = 0, temp2 = 0;            if (i >= 0)                temp1 = num1[i] - '0';            if (j >= 0)                temp2 = num2[j] - '0';            int temp_res = (temp1 + temp2 + carry) % 10;            carry = (temp1 + temp2 + carry) / 10;            res = to_string(temp_res) + res;        }        if (carry)            res = to_string(carry) + res;        return res;    }};int main() {    Solution s;    cout << s.addStrings("11", "99") << endl;    system("pause");    return 0;}
0 0