Subtract the Product and Sum of Digits of an Integer Problem
#1281
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1281.
Given an integer number n, return the difference between the product of its digits and the sum of its digits.
Example 1:
Input: n = 234
Output: 15
Explanation:
Product of digits = 2 * 3 * 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15
Example 2:
Input: n = 4421
Output: 21
Explanation:
Product of digits = 4 * 4 * 2 * 1 = 32
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32 - 11 = 21
Constraints:
1 <= n <= 10^5
Solution
Approach: Peel Off the Digits
n % 10 is the last digit of n, and n / 10 (integer division) removes it. Repeating this until n is 0 visits every digit once. Keep a running product (starting at 1) and a running sum (starting at 0), and return their difference.
For n = 234, the digits come out as 4, 3, 2: the product is 24, the sum is 9, and the answer is 15. The answer can be negative: for n = 10, the product is 0 and the sum is 1, so the answer is -1.
Complexity: O(log n) time (one step per digit) and O(1) space.
class Solution:
def subtractProductAndSum(self, n: int) -> int:
product, total = 1, 0
while n > 0:
n, digit = divmod(n, 10)
product *= digit
total += digit
return product - total