Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1281. Subtract the Product and Sum of Digits of an Integer - Leetcode Solution

Code Implementation

class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        product = 1
        summation = 0
        while n > 0:
            digit = n % 10
            product *= digit
            summation += digit
            n //= 10
        return product - summation
      
class Solution {
public:
    int subtractProductAndSum(int n) {
        int product = 1;
        int sum = 0;
        while (n > 0) {
            int digit = n % 10;
            product *= digit;
            sum += digit;
            n /= 10;
        }
        return product - sum;
    }
};
      
class Solution {
    public int subtractProductAndSum(int n) {
        int product = 1;
        int sum = 0;
        while (n > 0) {
            int digit = n % 10;
            product *= digit;
            sum += digit;
            n /= 10;
        }
        return product - sum;
    }
}
      
var subtractProductAndSum = function(n) {
    let product = 1;
    let sum = 0;
    while (n > 0) {
        let digit = n % 10;
        product *= digit;
        sum += digit;
        n = Math.floor(n / 10);
    }
    return product - sum;
};
      

Problem Description

Given an integer n, you are asked to find the difference between the product of its digits and the sum of its digits. That is, for each digit in n, calculate the product of all digits, calculate the sum of all digits, and then return (product of digits) - (sum of digits).

  • The input is a single positive integer n.
  • You must use each digit of n exactly once in both product and sum calculations.
  • There is always one valid answer for any valid input.

Thought Process

To solve this problem, we need to process each digit of the integer n. For each digit, we want to keep track of two things: the running product (multiplying the digits together) and the running sum (adding the digits together). After processing all digits, we subtract the sum from the product.

The naive approach would be to convert the number to a string, loop through each character, convert it back to an integer, and update our product and sum. However, we can avoid the string conversion and use simple arithmetic instead: repeatedly take the last digit with n % 10, update the product and sum, and then remove the last digit with integer division n //= 10 (or n /= 10 in other languages).

This approach is efficient and direct, and it avoids unnecessary conversions or data structures.

Solution Approach

Here is a step-by-step breakdown of the algorithm:

  1. Initialize two variables: product to 1 (since 1 is the identity for multiplication), and sum to 0 (since 0 is the identity for addition).
  2. While n is greater than 0:
    • Extract the last digit: digit = n % 10.
    • Multiply product by digit.
    • Add digit to sum.
    • Remove the last digit from n: n = n // 10 (or language equivalent).
  3. After the loop, return product - sum.

This approach is optimal because:

  • It only loops once through all digits (O(d), where d is the number of digits in n).
  • No extra data structures are needed.
  • Mathematical operations are simple and efficient.

Example Walkthrough

Let's take n = 234 as an example.

  1. Initial values: product = 1, sum = 0, n = 234
  2. First iteration:
    • digit = 234 % 10 = 4
    • product = 1 * 4 = 4
    • sum = 0 + 4 = 4
    • n = 234 // 10 = 23
  3. Second iteration:
    • digit = 23 % 10 = 3
    • product = 4 * 3 = 12
    • sum = 4 + 3 = 7
    • n = 23 // 10 = 2
  4. Third iteration:
    • digit = 2 % 10 = 2
    • product = 12 * 2 = 24
    • sum = 7 + 2 = 9
    • n = 2 // 10 = 0
  5. Loop ends since n = 0.
  6. Final answer: product - sum = 24 - 9 = 15

This matches the expected output.

Time and Space Complexity

  • Brute-force approach: If you convert the number to a string and iterate, it takes O(d) time and O(d) space, where d is the number of digits.
  • Optimized approach (used here): Only O(d) time and O(1) extra space, since we use arithmetic to extract digits and only keep a few variables.

In both cases, the time complexity is linear in the number of digits (which is at most 10 for a 32-bit integer), so the algorithm is extremely efficient.

Summary

The key to this problem is recognizing that you can process each digit of n using simple arithmetic, updating a product and sum as you go. By avoiding unnecessary string conversions or data structures, the solution remains efficient and easy to understand. This approach is both optimal and elegant, making it a great example of direct digit manipulation in integer problems.