LeetCode - 字符串相乘

题目链接:https://leetcode-cn.com/problems/multiply-strings/

题目描述

给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。

示例1:

输入: num1 = “2”, num2 = “3”
输出: “6”

示例2:

输入: num1 = “123”, num2 = “456”
输出: “56088”

说明:
1.num1 和 num2 的长度小于110。
2.num1 和 num2 只包含数字 0-9。
3.num1 和 num2 均不以零开头,除非是数字 0 本身。
4.不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。

我的思路

  • 这是一道关于字符串乘法的算法题。
  • 这道题的难点在于 这道题是属于大数乘法,也就是用整型变量存储计算大数会溢出。
  • num1 和 num2 从低到高逐位计算,计算的时候需要计算进位,将进位保存在 count[i+j] 的位置,去掉进位后的结果保存在 count[i+j+1] 的位置。

代码如下:

class Solution {
public:
    string multiply(string num1, string num2) {
        if(num1 == "0" || num2 == "0") return "0";
        string res = "";
        int n = num1.size();
        int m = num2.size();
        vector<int> count(n+m, 0);
        int carry = 0;
        for(int i = n-1; i >= 0; i--){
            for(int j = m-1; j >= 0; j--){
                int cur = ((int)num1[i]-'0') * ((int)num2[j]-'0');	//计算乘积				
                count[i+j] += cur / 10;								//计算进位,将进位保存在 count[i+j]
                count[i+j+1] += cur % 10;							//计算去掉进位后的结果,保存在 count[i+j+1]
                if(count[i+j+1] >= 10){								//如果某位存储的结果不是只含个位的数,进行处理
                    count[i+j] += count[i+j+1] / 10;			
                    count[i+j+1] = count[i+j+1] % 10;
                }
            }
        }
        while(count[0] == 0) count.erase(count.begin());			//去掉前面的零
        for(int i = 0; i < count.size(); i++){
            res.append(to_string(count[i]));						//将int数组转成string字符串
        }
        return res;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值