Subtract The Product And Sum Of Digits Of An Integer

Easy
0/40
Average time to solve is 10m
profile
Contributed by
11 upvotes
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
Detailed explanation ( Input/output format, Notes, Images )
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
Sample Input 1 :
2
234
4421
Sample Output 1 :
15
21

Explanation For Sample Input 1 :

Product of digits = 2 * 3 * 4 = 24 
Sum of digits = 2 + 3 + 4 = 9 
Result = 24 - 9 = 15

Product of digits = 4 * 4 * 2 * 1 = 32 
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32 - 11 = 21
Sample Input 2 :
1
87
Sample Output 2 :
 41
Hint

Think about how can all the digits of the number be extracted?

Approaches (1)
Brute Force

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.
Time Complexity

O(digits), where ‘digits’ denote the number of digits present in the given number.

 

Since we are finding the product and sum for all the digits present in the number, therefore, the time complexity will be O(digits).

Space Complexity

O(1).

 

Since constant space is used.

Code Solution
(100% EXP penalty)
Subtract The Product And Sum Of Digits Of An Integer
Full screen
Console