Subtract the Product and Sum of Digits of an Integer
LeetCode Subtract the Product and Sum of Digits of an Integer (Problem 1281) gives you an integer n and asks you to return the difference between the product of its digits and the sum of its digits.
For example, given n = 234, you compute the product 2 * 3 * 4 = 24, the sum 2 + 3 + 4 = 9, and return 24 - 9 = 15.
Problem description
Given an integer n, return the difference between the product of its digits and the sum of its digits.
- Input:
n = 234 - Output:
15 - Explanation: Product of digits =
2 * 3 * 4 = 24. Sum of digits =2 + 3 + 4 = 9. Result =24 - 9 = 15.
The approach
This problem is a clean exercise in digit extraction. You need to pull each digit out of the number, accumulate a running product and a running sum, and then subtract at the end.
The core technique is the mod and div pattern: use n % 10 to get the rightmost digit, then n //= 10 to chop it off. You keep going until n reaches 0. If you have worked through Add Digits or Happy Number, you have already seen this exact loop.
The only twist here is that you maintain two accumulators instead of one. Initialize product to 1 (the multiplicative identity) and sum_digits to 0 (the additive identity). Each time you extract a digit, multiply it into the product and add it to the sum. After the loop, return product - sum_digits.
There are no tricky edge cases to worry about. The constraint says 1 <= n <= 10^5, so you will always have at least one digit and never encounter zero as an input. The result can be negative (for instance, n = 1 gives 1 - 1 = 0, and n = 11 gives 1 - 2 = -1), but that is fine since the problem just asks you to return the difference.
When a problem asks you to do something with "the digits" of a number, reach for the mod/div extraction pattern. It works for any base-10 digit operation, whether you are summing, multiplying, reversing, or checking palindromes.
The solution
def subtract_product_and_sum(n):
product = 1
sum_digits = 0
while n > 0:
digit = n % 10
product *= digit
sum_digits += digit
n //= 10
return product - sum_digits
A single pass through the digits is all you need. The loop runs once per digit in n. Each iteration extracts the last digit, updates both accumulators, and removes that digit from n. When the loop ends, you return the difference.
You could also solve this by converting n to a string and iterating over the characters:
def subtract_product_and_sum(n):
digits = [int(d) for d in str(n)]
product = 1
for d in digits:
product *= d
return product - sum(digits)
Both approaches work. The numeric version avoids string conversion and is a better demonstration of the mod/div pattern that shows up repeatedly in digit-manipulation problems.
Step-by-step walkthrough
Let's trace through the numeric solution with n = 234.
Step 1: Extract the digits
[4, 3, 2]Use n % 10 to get the last digit, then n //= 10 to remove it. Repeat until n is 0.
Step 2: Compute the product
1 × 4 = 44 × 3 = 1212 × 2 = 24Multiply all the digits together. Start with product = 1 and multiply each digit in.
Step 3: Compute the sum
0 + 4 = 44 + 3 = 77 + 2 = 9Add all the digits together. Start with sum = 0 and add each digit.
Step 4: Subtract
product - sum = 24 - 9 = 15The final answer is always product minus sum. One subtraction and you are done.
Each step does the same thing: extract a digit, multiply it into the product, add it to the sum. After processing all three digits, you subtract and return.
Complexity analysis
| Aspect | Value |
|---|---|
| Time | O(log n), one pass through each digit |
| Space | O(1), only a few integer variables |
The number of digits in n is proportional to log base 10 of n. Since you process each digit exactly once, the time complexity is O(log n). You use a constant amount of extra space regardless of the input size.
Building blocks
This problem breaks down into reusable pieces you will see in many other problems.
1. Digit extraction with mod and div
The pattern digit = n % 10 followed by n //= 10 peels off digits from right to left. You have seen this same loop in Palindrome Number, Happy Number, and Add Digits. Once you internalize this pattern, any problem that says "do something with the digits" becomes approachable.
while n > 0:
digit = n % 10
n //= 10
2. Dual accumulators
Maintaining two running values (product and sum) through the same loop is a minor but useful pattern. It shows up whenever you need to compute multiple aggregate values in a single pass, for example tracking both a minimum and maximum, or both a count and a total.
Edge cases
- Single-digit number (
n = 5): Product is 5, sum is 5, result is5 - 5 = 0. Any single-digit input returns 0. - Number with a zero digit (
n = 10): Product is1 * 0 = 0, sum is1 + 0 = 1, result is0 - 1 = -1. The zero in the number collapses the product to zero. - All ones (
n = 111): Product is1 * 1 * 1 = 1, sum is1 + 1 + 1 = 3, result is1 - 3 = -2. When digits are all ones, the sum always exceeds the product for numbers with more than one digit. - Large digits (
n = 99999): Product is9^5 = 59049, sum is9 * 5 = 45, result is59049 - 45 = 59004. Products grow much faster than sums when digits are large.
From understanding to recall
Reading through this solution takes just a couple of minutes. The logic is clear: extract digits, multiply, add, subtract. But will you remember the mod/div extraction pattern the next time you see a digit-manipulation problem in an interview?
That is where spaced repetition helps. CodeBricks breaks this problem into its building blocks, the digit extraction loop and the dual-accumulator pattern, and drills them at increasing intervals. You type the code from scratch each time, building real muscle memory rather than passive familiarity. After a few review sessions, reaching for n % 10 and n //= 10 becomes second nature.
Related posts
- Add Digits - Another digit-processing problem using the same mod/div extraction loop, with a bonus O(1) digital root formula
- Happy Number - Digit extraction combined with cycle detection, showing how the same building block appears in a harder context
- Palindrome Number - Digit manipulation without string conversion, reversing half the number using mod and div