Subtract the Product and Sum of Digits of an Integer
Easy
Topics
Given an integer n, return the product of its digits minus the sum of its digits.
Example 1
Cells are the digits of 234. Their product is 24 and their sum is 9, so the answer is 24 − 9 = 15.
Cells are the decimal digits.
Input: n = 234 Output: 15 Explanation: product = 24, sum = 9, 24 - 9 = 15.
Example 2
Input: n = 4421 Output: 21
Constraints
- 1 <= n <= 10^5
Editorial — intuition, approach, complexity and pitfalls
Intuition
Two accumulators over the digits: a product and a sum, then subtract. The digits come out with n % 10 and n //= 10, which needs no string conversion.
The only thing to be careful of is the product's starting value: it must be 1, the multiplicative identity. Starting at 0 makes every product 0.
Approach
product = 1,total = 0.- While
n > 0: taken % 10, multiply into the product, add to the total, dividenby 10. - Return
product - total.
Dry Run
n = 234
d=4 product 4 total 4 n=23
d=3 product 12 total 7 n=2
d=2 product 24 total 9 n=0
answer 24 - 9 = 15
n = 4421
d=1 -> p 1, s 1
d=2 -> p 2, s 3
d=4 -> p 8, s 7
d=4 -> p 32, s 11
answer 32 - 11 = 21Complexity
- Time — O(log n): one iteration per digit.
- Space — O(1): two accumulators. Converting to a string would be O(log n) for the characters.
Common Pitfalls
- Initialising the product to 0, which returns the negated digit sum for every input.
- Looping on
n != 0with a potentially negative input. The constraints start at 1, so it cannot arise here. - Returning
sum - product. The order is product first. - Worrying about a zero digit. It correctly zeroes the product, which is the defined behaviour.
Full Solution — all languages
class Solution:
def subtractProductAndSum(self, n):
product, total = 1, 0
while n > 0:
d = n % 10
product *= d
total += d
n //= 10
return product - totalimport java.util.*;
class Solution {
public int subtractProductAndSum(int n) {
int product = 1, total = 0;
while (n > 0) {
int d = n % 10;
product *= d;
total += d;
n /= 10;
}
return product - total;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int subtractProductAndSum(int n) {
int product = 1, total = 0;
while (n > 0) {
int d = n % 10;
product *= d;
total += d;
n /= 10;
}
return product - total;
}
};/**
* @param {number} n
* @return {number}
*/ var subtractProductAndSum = function(n) {
let product = 1, total = 0;
while (n > 0) {
const d = n % 10;
product *= d;
total += d;
n = Math.floor(n / 10);
}
return product - total;
};