ProDeveloperTutorial.com

教程和国彩网解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统国彩网
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

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

前开发者教程 八月9,2018

范例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+章
分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性国彩网问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和国彩网解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的


    <address id="Rwfzdxu"></address>



  • <ruby id="QjKeVJF" class="Q2QYbzO"><ins id="t6jz3vl" class="ti72ECl"></ins></ruby>
    <video id="aQavcOR"><dd class="mULdPfK"></dd></video>

  • <dfn class="prSbISL"><legend class="WvHiSpZ"><option id="wzQozqr" class="wMtaggg"><footer id="juoQ66Z"></footer></option></legend></dfn>


        <section id="WV3xe1m"></section>



          • <code id="jP8xFcm"></code>