范例1:
Input: num1 = "2", num2 = "3" Output: "6"
范例2:
Input: num1 = "123", num2 = "456" Output: "56088"
首先,我们将看看如何进行正态乘法:
如果我们尝试将整数相乘 num_1 =“ 1 2 3” 与 num_2 =“ 4 5 6”,以下是我们遵循的步骤:
第1步: 从num_2的右侧开始,取一位数字并与num_1的所有数字相乘。
第2步: 当我们转到num_2的第二个数字时,我们在结果右侧保留一个空格。同样,我们为3rd 数字,我们在右侧保留2个空格。
第三步: 然后,我们将所有数字相加以获得最终结果。
注意: 在相乘时,数字有可能会进位,然后我们需要将其进位到下一位。
以上三个步骤可以如下图所示:
首先乘以6:
乘以5:
乘以4:
总计结果:
现在我们已经介绍了基本知识,如何通过国彩网实现它?
考虑下图,我们试图得到“ 1 2 3 [绿色]” *“ 4 5 [蓝色]”的结果。
从下图可以得出结论:
`num_1[i] * num_2[j]` will be placed at indices `[i + j`, `i + j + 1]`
因此,我们可以使用C ++以国彩网方式编写它,如下所示:
/* * File : multiply_strings.cpp */ #include<iostream> using namespace std; string multiply_strings(string num_1, string num_2) { int len_1 = num_1.length(); int len_2 = num_2.length(); //create space to store the result and fill it 与 zero's string final_result(len_1 + len_2, '0'); //reverse both number 1 and number 2, bacause we calcuate it from reverse reverse(num_1.begin(), num_1.end()); reverse(num_2.begin(), num_2.end()); //we use 2 loops because, we have to multiply 2 numbers for (int i = 0; i < len_1; i++) { for (int j = 0; j < len_2; j++) { int tmp_result = (final_result[i + j] - '0') + (num_1[i] - '0') * (num_2[j] - '0'); // we use num_1[i] - '0' as it will give the integer value of that number final_result[i + j] = '0' + tmp_result % 10; final_result[i + j + 1] += tmp_result / 10; } } for (int i = len_1 + len_2 - 1; i > 0 && final_result[i] == '0'; i--) final_result.pop_back(); reverse(final_result.begin(), final_result.end()); return final_result; } int main() { string num_1 = "123"; string num_2 = "456"; string result = multiply_strings(num_1, num_2); cout << "The result of "<<num_1 <<" * "<<num_2 <<" is = "<<result<<endl; return 0; }
输出:
The result of 123 * 456 is = 56088
使用网格乘法也可以解决此问题。如果有人可以为此编写解决方案,它将很有用。我将尽快提供解决方案。
该网站上可用的教程列表:
C国彩网20+章 | C ++国彩网80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统国彩网20+章 |