给定两个正整数N1和N2 ,任务是查找两个数字的相同位数的乘积之和。
注意:对于长度不相等的数字,较小数字的前几位需要视为0。
例子:
Input: N1 = 5, N2 = 67
Output: 35
Explanation:
At one’s place, we have digits 5 and 7, their product is 35. At ten’s place we have 6 in N2. As N1 has no digit at ten’s place, 6 will be multiplied with 0, leading to no effect on the sum. Hence, the calculated sum is 35.
Input: N1 = 25, N2 = 1548
Output: 48
Explanation:
Sum = 5 * 8 + 2 * 4 + 0 * 5 + 0 * 1 = 48.
方法:
要解决上述问题,我们需要执行以下步骤:
- 提取两个数字的最右边的数字,并将它们相乘,然后将其乘积相加。
- 现在删除数字。
- 继续重复上述两个步骤,直到其中之一减小为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