Subtract the Product and Sum of Digits of an Integer in C++

C++Server Side ProgrammingProgramming

Suppose we have one number. We have to find the sum of digits and product of digits. After that find the difference between sum and product. So if the number is 5362, then sum is 5 + 3 + 6 + 2 = 16, and 5 * 3 * 6 * 2 = 180. So 180 – 16 = 164

To solve this take each digit and add and multiply one by one, then return the difference.

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
      int subtractProductAndSum(int n) {
         int prod = 1;
         int sum = 0;
         for(int t = n;t;t/=10){
            sum += t % 10;
            prod *= t % 10;
         }
         return prod - sum;
      }
};
main(){
   Solution ob;
   cout << ob.subtractProductAndSum(5362);
}

Input

5362

Output

164
raja
Published on 20-Jan-2020 11:22:48
Advertisements