Subtract the Product and Sum of Digits of an Integer

easy math digits

Problem

Take a positive integer n (1 ≤ n ≤ 10⁵) and look at its decimal digits. Multiply all the digits together to get a product, add them all up to get a sum, and return product − sum.

Inputn = 234
Output15
Digits are 2, 3, 4: product = 2·3·4 = 24, sum = 2+3+4 = 9, and 24 − 9 = 15.

def subtract_product_and_sum(n):
    product, total = 1, 0
    while n > 0:
        d = n % 10
        product *= d
        total += d
        n //= 10
    return product - total
function subtractProductAndSum(n) {
  let product = 1, sum = 0;
  while (n > 0) {
    const d = n % 10;
    product *= d;
    sum += d;
    n = Math.floor(n / 10);
  }
  return product - sum;
}
int subtractProductAndSum(int n) {
    int product = 1, sum = 0;
    while (n > 0) {
        int d = n % 10;
        product *= d;
        sum += d;
        n /= 10;
    }
    return product - sum;
}
int subtractProductAndSum(int n) {
    int product = 1, sum = 0;
    while (n > 0) {
        int d = n % 10;
        product *= d;
        sum += d;
        n /= 10;
    }
    return product - sum;
}
Time: O(log n) Space: O(1)