(C++)字符串相乘

个人主页:Lei宝啊

愿所有美好如期而遇


题目链接如下:

力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。https://leetcode-cn.com/problems/multiply-strings/description/

题目

思路

我们首先不能将字符串全部转换为数字,因为存储不下,而且注意也不允许,所以我们应该想到用一个字符串尾部的单位乘一个字符串,然后存储得到的字符串,再由尾部的倒数第二位乘,再存储结果字符串,并且根据位数在结果字符串后补0,最终得到的所有结果字符串相加,就是我们的答案。

字符串相加:(C++)字符串相加

图解

代码

复制代码
string multiply(string num1, string num2) 
    {
        if(num1 == "0" || num2 == "0")
        {
            return "0";
        }

        int s1 = num1.size();
        int s2 = num2.size();

        if(s1 > s2)
        {
            num1.swap(num2);
            s1 = num1.size();
            s2 = num2.size();
        }

        int count = 0;
        string s[201];
        for(int i=s1-1; i>=0; i--)
        {

            int ch1 = num1[i] - 48;
            int add = 0;

            for(int j=s2-1; j>=0; j--)
            {
                int ch2 = num2[j] - 48;
                s[i] += ch2 * ch1 % 10 + 48 + add;
                add = ch2 * ch1 / 10;     
            }
            if(add > 0)
            {
                s[i] += add + 48;
            }
            reverse(s[i].begin(),s[i].end());

            for(int k=0; k<count; k++)
            {
                s[i] += '0';
            }
            count++;
        }

        string result;
        for(int i=0; i<s1; i++)
        {
            result = addStrings(result,s[i]);
        }

        return result;
    }

string addStrings(string num1, string num2) 
    {
        string result;
        int next = 0;
 
        char tmp1 = 0;
        char tmp2 = 0;
 
        while(!num1.empty() || !num2.empty())
        {
            if(!num1.empty())
                tmp1 = num1[num1.size()-1] - 48;
            else
                tmp1 = 0;
 
            if(!num2.empty())
                tmp2 = num2[num2.size()-1] - 48;
            else
                tmp2 = 0;
 
            int sum = tmp1 + tmp2 + next;
            next = sum / 10;
            sum %= 10;
 
            result += (sum+48);
 
            if(!num1.empty())
                num1.erase(num1.end()-1);
            if(!num2.empty())
                num2.erase(num2.end()-1);
        }
 
        if(next > 0)
            result += '1';
 
        reverse(result.begin(),result.end());
        return result;
    }   
相关推荐
草莓熊Lotso6 天前
【洛谷题单】--分支结构(三)
c语言·c++·刷题·洛谷
草莓熊Lotso10 天前
【洛谷题单】--分支结构(二)
c语言·c++·经验分享·其他·刷题
草莓熊Lotso17 天前
【LeetCode刷题指南】--单值二叉树,相同的树
c语言·数据结构·算法·leetcode·刷题
Lenyiin21 天前
《LeetCode 热题 100》整整 100 题量大管饱题解套餐 中
java·c++·python·leetcode·面试·刷题·lenyiin
草莓熊Lotso24 天前
【LeetCode刷题指南】--有效的括号
c语言·数据结构·其他·算法·leetcode·刷题
草莓熊Lotso1 个月前
【数据结构初阶】--双向链表(二)
c语言·数据结构·经验分享·链表·刷题
草莓熊Lotso1 个月前
【LeetCode刷题指南】--数组串联,合并两个有序数组,删除有序数组中的重复项
c语言·数据结构·其他·刷题
charlie1145141911 个月前
我的Qt八股文笔记2:Qt并发编程方案对比与QPointer,智能指针方案
笔记·qt·面试·刷题·并发编程·异步
凤年徐1 个月前
【数据结构与算法】203.移除链表元素(LeetCode)图文详解
c语言·开发语言·数据结构·算法·leetcode·链表·刷题
草莓熊Lotso1 个月前
【洛谷题单】--顺序结构(一)
c语言·c++·其他·刷题