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;
    }
};
相关推荐
不会就选b8 小时前
C++补充部分(一)--lambda 表达式
开发语言·c++
lvwangshu15 小时前
方阵游戏 题解
题解·技巧·前缀优化·性质题·思维好题·推导题
丰色木夕16 小时前
Ubuntu22.04下源码编译安装USD-Brep
c++·ubuntu·nvidia·usd-brep
文丑颜不良啊16 小时前
LeetCode51~75题目解析
leetcode
学电子她就能回来吗16 小时前
LeetCode Hot 100|普通数组专题学习笔记(零基础版)
笔记·算法·leetcode
衍玊18 小时前
多路转接原理与应用
c++
himobrinehacken20 小时前
位运算揭秘:左右移与符号位陷阱
c语言·c++·算法·安全
文丑颜不良啊21 小时前
LeetCode1~50题目解析
leetcode
Pniubi21 小时前
力扣146.LRU缓存机制
算法·leetcode·缓存
Android小码家1 天前
Vehicle 实战 自定义属性+测试demo
java·c++·framework·vhal·vehicle