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

Number: 1406

Difficulty: Easy

Paid? No

Companies: Meta, Quora


Problem Description

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


Key Insights

  • Iterate through each digit of the integer.
  • Multiply the digits together for the product.
  • Add the digits together for the sum.
  • The result is the product minus the sum.

Space and Time Complexity

Time Complexity: O(d), where d is the number of digits in n.
Space Complexity: O(1), constant extra space.


Solution

The solution involves processing each digit of the integer n. We can either convert the integer to a string or use arithmetic operations to extract each digit by repeatedly taking the modulo and division by 10. We initialize two variables: one for the product (initialized to 1) and one for the sum (initialized to 0). For every digit, we update the product and the sum. Finally, the difference (product - sum) is returned. This method is efficient and straightforward, requiring constant space.


Code Solutions

# Function to calculate the difference between product and sum of digits
def subtractProductAndSum(n: int) -> int:
    product = 1     # Initialize product of digits
    digit_sum = 0   # Initialize sum of digits
    # Process each digit until n becomes 0
    while n > 0:
        digit = n % 10           # Extract the last digit
        product *= digit         # Multiply product by the digit
        digit_sum += digit       # Add digit to the sum
        n //= 10                 # Remove the last digit
    return product - digit_sum   # Return the difference between product and sum

# Example usage
print(subtractProductAndSum(234))  # Expected output: 15
← Back to All Questions