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.
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.
O(log n) time and O(1) space.
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
}
class Solution:
def subtractProductAndSum(self, n: int) -> int:
product, total = 1, 0
while n:
n, digit = divmod(n, 10); product *= digit; total += digit
return product - total
function subtractProductAndSum(n: number): number {
let product = 1; let sum = 0;
while (n > 0) { const digit = n % 10; product *= digit; sum += digit; n = Math.floor(n / 10); }
return product - sum;
}