Sum of the Product of digits of all Array elements
Last Updated :
29 Dec, 2021
Given an array arr, the task is to find the sum of the product of digits of all array elements
Example:
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
Approach: To solve this problem, find the product of digits of all numbers and then just add them up. Follow the below steps to solve this problem:
- Create a function findProduct which will get a number and find the product of its digits.
- Create a variable sum to store the final answer and initialise it with 0.
- Now, traverse the array and for each element:
- Pass it to the function findProduct and get the product of its digit.
- Then add its product of digit to sum.
- Return sum as the final answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findProduct( int N)
{
if (N == 0) {
return 0;
}
int product = 1;
while (N > 0) {
product *= (N % 10);
N /= 10;
}
return product;
}
int sumOfProduct(vector< int > arr)
{
int sum = 0;
for ( auto x : arr) {
sum += findProduct(x);
}
return sum;
}
int main()
{
vector< int > arr = { 46, 32, 78, 0 };
cout << sumOfProduct(arr);
}
|
Java
import java.util.*;
public class GFG {
static int findProduct( int N)
{
if (N == 0 ) {
return 0 ;
}
int product = 1 ;
while (N > 0 ) {
product *= (N % 10 );
N /= 10 ;
}
return product;
}
static int sumOfProduct( int []arr)
{
int sum = 0 ;
for ( int i = 0 ; i < arr.length; i++) {
sum += findProduct(arr[i]);
}
return sum;
}
public static void main(String args[])
{
int []arr = { 46 , 32 , 78 , 0 };
System.out.println(sumOfProduct(arr));
}
}
|
Python3
def findProduct(N):
if (N = = 0 ):
return 0
product = 1
while (N > 0 ):
product * = (N % 10 )
N = N / / 10
return product
def sumOfProduct(arr):
sum = 0
for x in arr:
sum + = findProduct(x)
return sum
arr = [ 46 , 32 , 78 , 0 ]
print (sumOfProduct(arr))
|
C#
using System;
class GFG {
static int findProduct( int N)
{
if (N == 0) {
return 0;
}
int product = 1;
while (N > 0) {
product *= (N % 10);
N /= 10;
}
return product;
}
static int sumOfProduct( int []arr)
{
int sum = 0;
for ( int i = 0; i < arr.Length; i++) {
sum += findProduct(arr[i]);
}
return sum;
}
public static void Main()
{
int []arr = { 46, 32, 78, 0 };
Console.Write(sumOfProduct(arr));
}
}
|
Javascript
<script>
function findProduct(N) {
if (N == 0) {
return 0;
}
let product = 1;
while (N > 0) {
product *= (N % 10);
N = Math.floor(N / 10)
}
return product;
}
function sumOfProduct(arr) {
let sum = 0;
for (let x of arr) {
sum += findProduct(x);
}
return sum;
}
let arr = [46, 32, 78, 0];
document.write(sumOfProduct(arr));
</script>
|
Time Complexity: O(NlogM), where N is the size of the array and M is the maximum number in the array
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...