Sum of the Product of digits of all Array elements
Given an array arr, the task is to find the sum of the product of digits of all array elements
Example:
Hey! Looking for some great resources suitable for young ones? You've come to the right place. Check out our self-paced courses designed for students of grades I-XII.
Start with topics like Python, HTML, ML, and learn to make some games and apps all with the help of our expertly designed content! So students worry no more, because GeeksforGeeks School is now here!
Input: arr[]={11, 23, 41}
Output: 11
Explanation: 1*1 + 2*3 + 4*1 = 1 + 6 + 4 = 1111Input: 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++
// C++ code for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the product of the// digits of a number Nint 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 elementsint sumOfProduct(vector<int> arr){ int sum = 0; for (auto x : arr) { sum += findProduct(x); } return sum;} // Driver Codeint main(){ vector<int> arr = { 46, 32, 78, 0 }; cout << sumOfProduct(arr);} |
86
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)

