[Leetcode] Multiply Strings

本文提供了一种解决大数乘法问题的C++实现方案,通过字符串操作处理任意大的整数乘法,并特别注意了前置0的情况。该算法采用逐位相乘的方式,模拟了手算乘法的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.

 

大数乘法,注意前置0的处理。

 

 1 class Solution {
 2 public:
 3     string multiply(string num1, string num2) {
 4         string num3;
 5         num3.resize(num1.size() + num2.size());
 6         reverse(num1.begin(), num1.end());
 7         reverse(num2.begin(), num2.end());
 8         int carry = 0;
 9         int val;
10         int i, j, k;
11         for (i = 0; i < num3.size(); ++i) {
12             num3[i] = '0';
13         }
14         for (i = 0; i < num1.size(); ++i) {
15             carry = 0;
16             for (j = 0; j < num2.size(); ++j) {
17                 val = (num3[i+j] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry;
18                 carry = val / 10;
19                 val %= 10;
20                 num3[i+j] = '0' + val;
21             }
22             num3[i + j] = '0' + carry;
23         }
24         int prezero = 0;
25         for (i = num3.size() - 1; i > 0; --i) {
26             if (num3[i] == '0') 
27                 prezero++;
28             else 
29                 break;
30         }
31         num3.resize(num3.size() - prezero);
32         reverse(num3.begin(), num3.end());
33         return num3;
34     }
35 };

 

转载于:https://www.cnblogs.com/easonliu/p/3634951.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值