We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Subtract the Product and Sum of Digits of an Integer

Difficulty: Easy


Problem Description

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


Key Insights

  • The problem requires processing each digit of the integer n.
  • The product of digits is obtained by multiplying all the individual digits.
  • The sum of digits is obtained by adding all the individual digits.
  • The final result is the difference between the product and the sum.

Space and Time Complexity

Time Complexity: O(d), where d is the number of digits in n.
Space Complexity: O(1), as we only use a fixed amount of extra space.


Solution

To solve this problem, we can extract each digit of the integer n and calculate both the product and the sum of those digits. We can achieve this by using a loop that divides n by 10 to get the last digit and uses the modulo operator. We maintain two variables, one for the product and one for the sum. At the end of the loop, we return the difference between the product and sum.


Code Solutions

def subtractProductAndSum(n: int) -> int:
    product = 1
    summation = 0
    
    while n > 0:
        digit = n % 10  # Get the last digit
        product *= digit  # Multiply to the product
        summation += digit  # Add to the sum
        n //= 10  # Remove the last digit
    
    return product - summation  # Return the difference
← Back to All Questions