Category : Easy

**Problem**

Given an integer number `n`

, return the difference between the product of its digits and the sum of its digits.

https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/

**Examples**

**Example 1:**

1 2 3 4 5 6 | Input: n = 234 Output: 15 Explanation: Product of digits = 2 * 3 * 4 = 24 Sum of digits = 2 + 3 + 4 = 9 Result = 24 - 9 = 15 |

**Example 2**:

1 2 3 4 5 6 | Input: n = 4421 Output: 21 Explanation: Product of digits = 4 * 4 * 2 * 1 = 32 Sum of digits = 4 + 4 + 2 + 1 = 11 Result = 32 - 11 = 21 |

**Constraints**

`1 <= n <= 10^5`

**Solution Approach**

In this question, you just need to find the sum and product of the digits of a given number subtract it and return the difference. The only trivial thing in this question is to separate the digits and find the sum and product using those.

To solve this question we need to initialise 2 variables sum as 0 and product as 1 and we will store the sum and product in those respective variables. To separate the digits we run a loop where we take out the last digit by using the mod operation with 10. Then we multiply the digit to the product and add it to the sum variables. At the end of the loop, we decrease the number by removing its last digit. As the question requires I return product-sum as the answer.

**Solution code**

1 2 3 4 5 6 7 8 9 10 11 12 13 | class Solution { public int subtractProductAndSum(int n) { int product = 1; int sum = 0; while(n!=0){ int digit = n%10; product *= digit; sum += digit; n = n/10; } return (product-sum); } } |

For more Leetcode explained solutions visit Leetcode Solutions.

If you like capture the flag challenges visit here.

Check out my socials below in the footer. Feel free to ask any doubts in the comment section or contact me via Contact page I will surely respond. Happy Leetcoding