LeetCode 43. Multiply Strings (竖式乘法)C++

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"

Note:

The length of both num1 and num2 is < 110.
Both num1 and num2 contain only digits 0-9.
Both num1 and num2 do not contain any leading zero, except the number 0 itself.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
num1 和 num2 的长度小于110。
num1 和 num2 只包含数字 0-9。
num1 和 num2 均不以零开头,除非是数字 0 本身。
不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。

竖式乘法

在这里插入图片描述
用String类型的 res 表示计算结果
res[i+j+1] 累加储存 sum%10res[i+j] 累加储存 sum/10

res[i+j] += sum/10+=表示累加,
res[i+j+1] = sum % 10 + '0'不用+=
是因为前面的操作int sum = (num1[i] - '0')*(num2[j] - '0') + (res[i+j+1]-'0');sum已经累加了res[i+j+1]

C++

class Solution {
public:
    string multiply(string num1, string num2) {
		int n1=num1.size();
        int n2=num2.size();
        string res(n1+n2,'0');//2数相乘, 商的长度必定不可能大于2数的长度之和 size1 + size2
        for(int i=n1-1;i>=0;i--){
            for(int j=n2-1;j>=0;j--){
            	int sum = (num1[i] - '0')*(num2[j] - '0') + (res[i+j+1]-'0');
				res[i+j+1] = sum % 10 + '0';
				res[i+j] += sum/10; //string 内的字符 加上int 自动转化为char,不必加'0'
            }
        }
        //消前置零
        for(int i = 0; i < n1+n2; i++){
        	if(res[i]!='0'){
        		return res.substr(i);
			}
		}
        return "0";
    }
};

参考C++ 竖式乘法 代码简洁优雅易懂

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值