Last Updated: 17 Mar, 2021

Subtract The Product And Sum Of Digits Of An Integer

Easy
Asked in companies
UberGoogle inc

Problem statement

You are given an integer number ‘N’, and your task is to return the difference between the product of its digits and the sum of its digits.

Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
For Example :
Input: N = 234
Output: 15 
Explanation: 
Product of digits = 2 * 3 * 4 = 24 
Sum of digits = 2 + 3 + 4 = 9 
Result = 24 - 9 = 15
Input Format :
The first line of input contains a single integer ‘T’ denoting the number of test cases.

The second line contains the integer ‘N’ whose difference between the product and the sum of all the digits need to be calculated.
Output Format :
For each test case print the difference between the product and the sum of all the digits in ‘N’.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 3000
1 <= N <= 10^5

Time Limit: 1 sec

Approaches

01 Approach

The idea here is to traverse through all the digits in the number and keep calculating the product and sum for each digit until the sum and products of all the digits are obtained.

The algorithm will be-

  1. We will initialise a variable ‘prod’ with 1 and ‘sum’ with 0.
  2. Now we iterate over the digits of the given number and find the product and sum for that digit. We will use the modulus operator to calculate the digits present in the given number. i.e. We will find ‘N’ % 10 in every iteration.
  3. We initialise the ‘product’ with a value 1 and ‘sum’ with a value of 0 and for each digit that we get, we use it to find the product and sum up till that digit.
  4. At last, we will return the difference between the total product and the sum that we obtained.