所有 Array 元素的数字乘积之和
给定一个数组arr ,任务是找到所有数组元素的数字乘积之和
例子:
Input: arr[]={11, 23, 41}
Output: 11
Explanation: 1*1 + 2*3 + 4*1 = 1 + 6 + 4 = 1111
Input: arr[]={46, 32, 78, 0}
Output: 86
方法:为了解决这个问题,找到所有数字的数字的乘积,然后将它们相加。请按照以下步骤解决此问题:
- 创建一个函数findProduct ,它将获取一个数字并找到其数字的乘积。
- 创建一个变量sum来存储最终答案并将其初始化为 0。
- 现在,遍历数组和每个元素:
- 将其传递给函数findProduct并获取其数字的乘积。
- 然后将它的 digit 乘积加到sum中。
- 返回总和作为最终答案。
下面是上述方法的实现:
C++
// C++ code for the above approach
#include
using namespace std;
// Function to find the product of the
// digits of a number N
int findProduct(int N)
{
if (N == 0) {
return 0;
}
int product = 1;
while (N > 0) {
product *= (N % 10);
N /= 10;
}
return product;
}
// Function to find the sum of the product of
// digits of all array elements
int sumOfProduct(vector arr)
{
int sum = 0;
for (auto x : arr) {
sum += findProduct(x);
}
return sum;
}
// Driver Code
int main()
{
vector arr = { 46, 32, 78, 0 };
cout << sumOfProduct(arr);
}
Java
// Java code to implement above approach
import java.util.*;
public class GFG {
// Function to find the product of the
// digits of a number N
static int findProduct(int N)
{
if (N == 0) {
return 0;
}
int product = 1;
while (N > 0) {
product *= (N % 10);
N /= 10;
}
return product;
}
// Function to find the sum of the product of
// digits of all array elements
static int sumOfProduct(int []arr)
{
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += findProduct(arr[i]);
}
return sum;
}
// Driver code
public static void main(String args[])
{
int []arr = { 46, 32, 78, 0 };
System.out.println(sumOfProduct(arr));
}
}
// This code is contributed by Samim Hossain Mondal.
Python3
# Python code for the above approach
# Function to find the product of the
# digits of a number N
def findProduct(N):
if (N == 0):
return 0
product = 1
while (N > 0):
product *= (N % 10)
N = N // 10
return product
# Function to find the sum of the product of
# digits of all array elements
def sumOfProduct(arr):
sum = 0
for x in arr:
sum += findProduct(x)
return sum
# Driver Code
arr = [46, 32, 78, 0]
print(sumOfProduct(arr))
# This code is contributed by Saurabh Jaiswal
C#
// C# code to implement above approach
using System;
class GFG {
// Function to find the product of the
// digits of a number N
static int findProduct(int N)
{
if (N == 0) {
return 0;
}
int product = 1;
while (N > 0) {
product *= (N % 10);
N /= 10;
}
return product;
}
// Function to find the sum of the product of
// digits of all array elements
static int sumOfProduct(int []arr)
{
int sum = 0;
for (int i = 0; i < arr.Length; i++) {
sum += findProduct(arr[i]);
}
return sum;
}
// Driver code
public static void Main()
{
int []arr = { 46, 32, 78, 0 };
Console.Write(sumOfProduct(arr));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出:
86
时间复杂度: O(NlogM),其中 N 是数组的大小,M 是数组中的最大数
辅助空间: O(1)