Subtract the Product and Sum of Digits of an Integer

Easy

Topics
Math

Given an integer n, return the product of its digits minus the sum of its digits.

Example 1

234
Cells are the digits of 234. Their product is 24 and their sum is 9, so the answer is 24 − 9 = 15.
Cells are the decimal digits.
Input:  n = 234
Output: 15
Explanation: product = 24, sum = 9, 24 - 9 = 15.

Example 2

4421
Input:  n = 4421
Output: 21

Constraints

  • 1 <= n <= 10^5
Editorial — intuition, approach, complexity and pitfalls

Intuition

Two accumulators over the digits: a product and a sum, then subtract. The digits come out with n % 10 and n //= 10, which needs no string conversion.

The only thing to be careful of is the product's starting value: it must be 1, the multiplicative identity. Starting at 0 makes every product 0.

Approach

  1. product = 1, total = 0.
  2. While n > 0: take n % 10, multiply into the product, add to the total, divide n by 10.
  3. Return product - total.

Dry Run

n = 234

d=4   product 4     total 4     n=23
d=3   product 12    total 7     n=2
d=2   product 24    total 9     n=0

answer 24 - 9 = 15

n = 4421
d=1 -> p 1,  s 1
d=2 -> p 2,  s 3
d=4 -> p 8,  s 7
d=4 -> p 32, s 11
answer 32 - 11 = 21

Complexity

  • Time — O(log n): one iteration per digit.
  • Space — O(1): two accumulators. Converting to a string would be O(log n) for the characters.

Common Pitfalls

  • Initialising the product to 0, which returns the negated digit sum for every input.
  • Looping on n != 0 with a potentially negative input. The constraints start at 1, so it cannot arise here.
  • Returning sum - product. The order is product first.
  • Worrying about a zero digit. It correctly zeroes the product, which is the defined behaviour.

Full Solution — all languages

class Solution:
    def subtractProductAndSum(self, n):
        product, total = 1, 0
        while n > 0:
            d = n % 10
            product *= d
            total += d
            n //= 10
        return product - total
SensAI
Beta
Tap the mic to stop voice mode