Subtract the Product and Sum of Digits of an Integer

The problem requires calculating the difference between the product of the digits of an integer n and the sum of its digits. Here’s a simple Python solution for this problem:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        product = 1
        sum_of_digits = 0

        while n > 0:
            digit = n % 10
            product *= digit
            sum_of_digits += digit
            n //= 10

        return product - sum_of_digits

Explanation

  1. Initialization: We initialize product as 1 and sum_of_digits as 0. These variables will hold the product and sum of the digits of n, respectively.

  2. Extracting Digits: We use a while loop to iterate through each digit of n. Inside the loop, we calculate digit as n % 10, which gives us the rightmost digit of n.

  3. Calculating Product and Sum: We then multiply product by digit and add digit to sum_of_digits.

  4. Updating n: We divide n by 10 (using n //= 10) to remove the rightmost digit, and continue the loop.

  5. Returning the Result: After the loop, we return the difference between product and sum_of_digits, as required by the problem statement.

title: Subtract the Product and Sum of Digits of an Integer excerpt: This covers the basic building blocks such as reducing the input value by chopping the rightmost digit, extract the rightmost digit by modulo with 10 and chopping the rightmost digit by integer division with 10. tags: extract-rightmost-digit reducing-input-value modulo-operator integer-division chop-rightmost-digit

Given an integer number n, return the difference between the product of its digits and the sum of its digits.

Example 1:

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:

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

Hints

  • How to compute all digits of the number?
  • Use modulus operator (%) to compute the last digit.
  • Generalise modulus operator idea to compute all digits.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# @param {Integer} n
# @return {Integer}
def subtract_product_and_sum(n)
  product = 1
  sum = 0
  
  while n > 0
    sum += n % 10  
    product *= n % 10
    n = n / 10
  end
  
  product - sum
end

Building Blocks

  • Reducing the Input Value by Chopping the Rightmost Digit
  • Extract the Rightmost Digit by Modulo with 10
  • Chopping the Rightmost Digit by Integer Division with 10