LeetCode 1281 · Bits · Math

Subtract the Product and Sum of Digits, explained with a picture

Rolling the digits like dice.

Bits · Math
▶ Watch it step by step

The problem

Return the product of a number’s digits minus the sum of its digits.

Input:  234
Output: 15   (2·3·4 = 24, 2+3+4 = 9)

Picture it

Picture rolling the digits like dice, one at a time from the end (n % 10), multiplying them into one total and adding them into another.

Short version: the full lesson (brute force, complexity, edge cases and a quiz) is still being written. The animation is complete.

The key idea

Peel digits with % and //. O(number of digits).

Python solution

def subtract_product_and_sum(n):
    prod, total = 1, 0
    while n:
        d = n % 10
        prod *= d
        total += d
        n //= 10
    return prod - total

In the interactive version each line lights up as the animation runs, and you can type your own input to see the algorithm handle it.