📌  相关文章
📜  两个数字相同位数的乘积之和

📅  最后修改于: 2021-05-04 18:10:08             🧑  作者: Mango

给定两个正整数N1和N2 ,任务是查找两个数字的相同位数的乘积之和。
注意:对于长度不相等的数字,较小数字的前几位需要视为0。
例子:

方法:
要解决上述问题,我们需要执行以下步骤:

  • 提取两个数字的最右边的数字,并将它们相乘,然后将其乘积相加
  • 现在删除数字。
  • 继续重复上述两个步骤,直到其中之一减小为0。然后,打印计算出的总和的最终值。

下面是上述方法的实现:

C++
// C++ program to calculate the
// sum of same placed digits
// of two numbers
#include 
using namespace std;
 
int sumOfProductOfDigits(int n1, int n2)
{
    int sum = 0;
     
    // Loop until one of the numbers
    // have no digits remaining
    while (n1 > 0 && n2 > 0)
    {
        sum += ((n1 % 10) * (n2 % 10));
        n1 /= 10;
        n2 /= 10;
    }
    return sum;
}
 
// Driver Code
int main()
{
    int n1 = 25;
    int n2 = 1548;
 
    cout << sumOfProductOfDigits(n1, n2);
}
 
// This code is contributed by grand_master


Java
// Java program to calculate the
// sum of same placed digits of
// two numbers
 
class GFG {
 
    // Function to find the sum of the
    // products of their corresponding digits
    static int sumOfProductOfDigits(int n1,
                                    int n2)
    {
        int sum = 0;
        // Loop until one of the numbers
        // have no digits remaining
        while (n1 > 0 && n2 > 0) {
            sum += ((n1 % 10) * (n2 % 10));
            n1 /= 10;
            n2 /= 10;
        }
 
        return sum;
    }
 
    // Driver Code
    public static void main(String args[])
    {
 
        int n1 = 25;
        int n2 = 1548;
 
        System.out.println(
            sumOfProductOfDigits(n1, n2));
    }
}


Python3
# Python3 program to calculate the
# sum of same placed digits
# of two numbers
 
def sumOfProductOfDigits(n1, n2):
 
    sum1 = 0;
     
    # Loop until one of the numbers
    # have no digits remaining
    while (n1 > 0 and n2 > 0):
 
        sum1 += ((n1 % 10) * (n2 % 10));
        n1 = n1 // 10;
        n2 = n2 // 10;
         
    return sum1;
 
# Driver Code
n1 = 25;
n2 = 1548;
 
print(sumOfProductOfDigits(n1, n2));
 
# This code is contributed by Nidhi_biet


C#
// C# program to calculate the
// sum of same placed digits of
// two numbers
using System;
class GFG{
 
// Function to find the sum of the
// products of their corresponding digits
static int sumOfProductOfDigits(int n1,
                                int n2)
{
    int sum = 0;
     
    // Loop until one of the numbers
    // have no digits remaining
    while (n1 > 0 && n2 > 0)
    {
        sum += ((n1 % 10) * (n2 % 10));
        n1 /= 10;
        n2 /= 10;
    }
    return sum;
}
 
// Driver Code
public static void Main()
{
    int n1 = 25;
    int n2 = 1548;
 
    Console.WriteLine(
            sumOfProductOfDigits(n1, n2));
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
48