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;
    }
};
相关推荐
AI视觉网奇7 小时前
Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr
开发语言·c++·算法
智者知已应修善业7 小时前
【输入两个数字,判断两数相乘是否等于各自逆序数相乘】2023-10-24
c语言·c++·经验分享·笔记·算法·1024程序员节
oioihoii7 小时前
C++11到C++23语法糖万字详解
java·c++·c++23
比昨天多敲两行7 小时前
C++入门基础
开发语言·c++
集3047 小时前
C++多线程学习笔记
c++·笔记·学习
ComputerInBook8 小时前
C++编程语言:标准库:第39章——本地化(语言环境)( Locales)(Bjarne Stroustrup)
c++·c++语言环境·c++ 本地化设置·c++ locale·c++ facet·语言特征
小武~8 小时前
Leetcode 每日一题C 语言版 -- 45 jump game ii
c语言·算法·leetcode
繁华似锦respect9 小时前
C++ 智能指针底层实现深度解析
linux·开发语言·c++·设计模式·代理模式
Bona Sun11 小时前
单片机手搓掌上游戏机(二十三)—esp32运行简单街机模拟器软硬件准备
c语言·c++·单片机
@小码农11 小时前
2025年北京海淀区中小学生信息学竞赛第二赛段C++真题
开发语言·数据结构·c++·算法