C++ | Leetcode C++题解之第43题字符串相乘

题目:

题解:

cpp 复制代码
class Solution {
public:
    string multiply(string num1, string num2) {
        if (num1 == "0" || num2 == "0") {
            return "0";
        }
        int m = num1.size(), n = num2.size();
        auto ansArr = vector<int>(m + n);
        for (int i = m - 1; i >= 0; i--) {
            int x = num1.at(i) - '0';
            for (int j = n - 1; j >= 0; j--) {
                int y = num2.at(j) - '0';
                ansArr[i + j + 1] += x * y;
            }
        }
        for (int i = m + n - 1; i > 0; i--) {
            ansArr[i - 1] += ansArr[i] / 10;
            ansArr[i] %= 10;
        }
        int index = ansArr[0] == 0 ? 1 : 0;
        string ans;
        while (index < m + n) {
            ans.push_back(ansArr[index]);
            index++;
        }
        for (auto &c: ans) {
            c += '0';
        }
        return ans;
    }
};
相关推荐
Pniubi2 小时前
01背包类问题-力扣416.分割等和子集
算法·leetcode·职场和发展
文丑颜不良啊12 小时前
LeetCode3041~3060题目解析
java·leetcode
eggwyw12 小时前
C++ union 的一种妙用法
开发语言·c++
文丑颜不良啊14 小时前
LeetCode3101~3120题目解析
java·leetcode
ShineWinsu14 小时前
对于Qt:QHBoxLayout常见属性以及方法的解析
c++·qt·面试·gui·客户端·布局管理器·水平布局器
小七在进步15 小时前
string的实现(1)
c++·笔记·visual studio
敲上瘾17 小时前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
牢姐与蒯18 小时前
cpp算法之哈希
c++·算法·哈希算法
lcj251119 小时前
[C++] C++11
开发语言·c++·笔记
玄昌盛不会编程21 小时前
LeetCode——2243. 计算字符串的数字和
java·算法·leetcode