Given two non-negative integers num1 and num2 represented
as strings, return the product of num1 and num2.
Note:
- The length of both
num1andnum2is < 110. - Both
num1andnum2contains only digits0-9. - Both
num1andnum2does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
1 class Solution
2 {
3 public:
4 string multiply(string num1, string num2)
5 {
6 vector<int> vi(num1.size() + num2.size(), 0);
7 for(int i = 0; i < num1.size(); ++ i)
8 for(int j = 0; j < num2.size(); ++ j)
9 vi[i + j] += (num1[num1.size() - i - 1] - '0') * (num2[num2.size() - j- 1] - '0');
10
11 for(int i = 0, c = 0; i < vi.size(); ++ i)
12 {
13 int num = vi[i] + c;
14 vi[i] = num % 10;
15 c = num / 10;
16 }
17
18 string s = "";
19 int i = vi.size();
20 while(-- i >= 0 && vi[i] == 0);
21 if(i < 0)
22 s = "0";
23 else
24 for( ; i >= 0; -- i)
25 s += vi[i] + '0';
26
27 return s;
28 }
29 };
本文介绍了一种不使用内置大数库或直接转换为整数的方法来计算两个非负整数的乘积。通过字符串表示这些整数,并利用逐位相乘再累加的方式,实现了大数间的乘法运算。
991

被折叠的 条评论
为什么被折叠?



