↓Skip to main content
  1. LeetCode/

LeetCode 1281: Subtract the Product and Sum of Digits of an Integer

·1 min· ·
LeetCode Easy Math
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2025-12-23

  • Submissions: Accepted (C++, first try)

Approach
#

Walk every digit, multiplying into a product that starts at 1 and adding into a sum that starts at 0, then return product - sum.

My Solution
#

I used C++ to_string to walk the digits; here is the equivalent Python:

class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        product, total = 1, 0
        while n:
            d = n % 10
            product *= d
            total += d
            n //= 10
        return product - total

Complexity
#

Time O(d), space O(1).

Mistakes to Avoid
#

  • The product starts at 1, not 0.

Interview Explanation
#

Peel digits with % 10, accumulating the product and sum together, then subtract. Time O(d).

Related

LeetCode 1512: Number of Good Pairs
·1 min
LeetCode Easy Math Hash-Table Counting Array
LeetCode 1512 note: count while scanning; each number pairs with every earlier equal number, so add its current count to the answer
LeetCode 2469: Convert the Temperature
·1 min
LeetCode Easy Math
LeetCode 2469 note: apply the formulas directly, Kelvin = C + 273.15 and Fahrenheit = C × 1.8 + 32
LeetCode 3697: Compute Decimal Representation
·1 min
LeetCode Easy Math Array
LeetCode 3697 note: each non-zero digit times its place value is one component; output them from the highest place down
LeetCode 3550: Smallest Index With Digit Sum Equal to Index
·1 min
LeetCode Easy Math Array
LeetCode 3550 note: check indices in increasing order, computing each digit sum; the first match is the answer
LeetCode 1979: Find Greatest Common Divisor of Array
·1 min
LeetCode Easy Math Number-Theory Gcd Array
LeetCode 1979 note: find the minimum and maximum, then take their GCD with Euclid’s algorithm
LeetCode 1486: XOR Operation in an Array
·1 min
LeetCode Easy Math Bit-Manipulation
LeetCode 1486 note: generate start + 2i by definition and XOR them together