09 Sept 2026Go / Python / TypeScriptEasy

Subtract the Product and Sum of Digits of an Integer

Subtract the sum of an integer's digits from the product of its digits.

Extract decimal digits one at a time, accumulating their product and sum, then return the difference.

complexity

O(log n) time and O(1) space.

solution files

  • Go subtract-the-product-and-sum-of-digits-of-an-integer/solution.go
  • Python subtract-the-product-and-sum-of-digits-of-an-integer/solution.py
  • TypeScript subtract-the-product-and-sum-of-digits-of-an-integer/solution.ts

Solution files

Gosubtract-the-product-and-sum-of-digits-of-an-integer/solution.go
package main

func subtractProductAndSum(n int) int {
	product, sum := 1, 0
	for n > 0 {
		digit := n % 10
		product *= digit
		sum += digit
		n /= 10
	}
	return product - sum
}
Pythonsubtract-the-product-and-sum-of-digits-of-an-integer/solution.py
class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        product, total = class="syntax-number">1, class="syntax-number">0
        while n:
            n, digit = divmod(n, class="syntax-number">10); product *= digit; total += digit
        return product - total
TypeScriptsubtract-the-product-and-sum-of-digits-of-an-integer/solution.ts
function subtractProductAndSum(n: number): number {
  let product = class="syntax-number">1; let sum = class="syntax-number">0;
  while (n > class="syntax-number">0) { const digit = n % class="syntax-number">10; product *= digit; sum += digit; n = Math.floor(n / class="syntax-number">10); }
  return product - sum;
}