美文网首页
Leetcode415. 字符串相加

Leetcode415. 字符串相加

作者: LonnieQ | 来源:发表于2019-11-07 00:50 被阅读0次

    题目

    给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。

    注意:

    num1 和num2 的长度都小于 5100.
    num1 和num2 都只包含数字 0-9.
    num1 和num2 都不包含任何前导零。
    你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。
    

    C++解法

    class Solution {
    public:
        string addStrings(string num1, string num2) {
            vector<int> lhs, rhs;
            string str;
            for (auto item: num1) lhs.push_back(item - '0');
            for (auto item: num2) rhs.push_back(item - '0');
            vector<int> result(max(lhs.size(), rhs.size()), 0);
            int i = 0;
            int flag = 0;
            while (i < lhs.size() || i < rhs.size()) {
                int index = (int)result.size() - i - 1;
                result[index] += flag;
                if (i < lhs.size()) result[index] += lhs[lhs.size() - i - 1];
                if (i < rhs.size()) result[index] += rhs[rhs.size() - i - 1];
                flag = (result[index] >= 10);
                result[index] %= 10;
                i++;
            }
            if (flag > 0) str.push_back('0' + flag);
            for (auto item: result) str.push_back('0' + item);
            return str;
        }
    };
    

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/add-strings

    相关文章

      网友评论

          本文标题:Leetcode415. 字符串相加

          本文链接:https://www.haomeiwen.com/subject/vofmbctx.html