Facebook Pixel

1281. Subtract the Product and Sum of Digits of an Integer

Problem Description

Given an integer number n, you need to find the difference between the product of its digits and the sum of its digits.

For example, if n = 234:

  • The digits are 2, 3, and 4
  • The product of digits = 2 × 3 × 4 = 24
  • The sum of digits = 2 + 3 + 4 = 9
  • The result = 24 - 9 = 15

The solution extracts each digit from the number n using the modulo operation (n % 10) to get the last digit, and integer division (n // 10) to remove the last digit. Two variables track the running product (x, initialized to 1) and running sum (y, initialized to 0) of all digits. After processing all digits, the function returns the difference x - y.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

To solve this problem, we need to extract each digit from the number and perform two operations: multiplication and addition. The key insight is that we can extract digits from a number using basic arithmetic operations.

When we divide any number by 10, the remainder gives us the last digit. For instance, 234 % 10 = 4. After extracting a digit, we can remove it by performing integer division: 234 // 10 = 23. This process can be repeated until the number becomes 0.

Since we need both the product and sum of all digits, we can calculate both values in a single pass through the number. We maintain two running values - one for the product (starting at 1, since multiplying by 1 doesn't change the value) and one for the sum (starting at 0, since adding 0 doesn't change the value). As we extract each digit, we multiply it into our running product and add it to our running sum.

This approach is efficient because we only need to traverse the digits once, and we don't need extra space to store all the digits separately. The mathematical operations divmod(n, 10) conveniently gives us both the quotient and remainder in one operation, making the code cleaner.

Learn more about Math patterns.

Solution Approach

The implementation uses a simulation approach to process each digit of the number one by one.

We initialize two variables:

  • x = 1 to store the product of digits (initialized to 1 because it's the multiplicative identity)
  • y = 0 to store the sum of digits (initialized to 0 because it's the additive identity)

The algorithm follows these steps:

  1. While n > 0, we continue processing digits:

    • Use divmod(n, 10) to simultaneously get:
      • The quotient (n // 10), which becomes the new value of n with the last digit removed
      • The remainder (n % 10), which is the current digit v
  2. For each extracted digit v:

    • Update the product: x = x * v
    • Update the sum: y = y + v
  3. After processing all digits (when n becomes 0):

    • Return the difference: x - y

The beauty of this approach is its simplicity - we process the number from right to left (least significant to most significant digit) using basic arithmetic operations. The divmod function elegantly handles both the digit extraction and the number reduction in a single operation.

For example, with n = 234:

  • First iteration: n = 23, v = 4, x = 1 * 4 = 4, y = 0 + 4 = 4
  • Second iteration: n = 2, v = 3, x = 4 * 3 = 12, y = 4 + 3 = 7
  • Third iteration: n = 0, v = 2, x = 12 * 2 = 24, y = 7 + 2 = 9
  • Return: 24 - 9 = 15

Ready to land your dream job?

Unlock your dream job with a 3-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through the solution with n = 52:

Initial Setup:

  • x = 1 (for product)
  • y = 0 (for sum)
  • n = 52

Iteration 1:

  • Extract digit: divmod(52, 10) gives quotient = 5, remainder = 2
  • Current digit v = 2
  • Update product: x = 1 × 2 = 2
  • Update sum: y = 0 + 2 = 2
  • Update n: n = 5

Iteration 2:

  • Extract digit: divmod(5, 10) gives quotient = 0, remainder = 5
  • Current digit v = 5
  • Update product: x = 2 × 5 = 10
  • Update sum: y = 2 + 5 = 7
  • Update n: n = 0

Final Step:

  • Loop ends since n = 0
  • Return difference: x - y = 10 - 7 = 3

The process systematically extracts each digit from right to left, maintaining running totals for both the product and sum, then returns their difference.

Solution Implementation

1class Solution:
2    def subtractProductAndSum(self, n: int) -> int:
3        """
4        Calculate the difference between the product and sum of digits of an integer.
5      
6        Args:
7            n: A positive integer
8          
9        Returns:
10            The difference between the product of all digits and the sum of all digits
11        """
12        product = 1  # Initialize product to 1 (multiplicative identity)
13        digit_sum = 0  # Initialize sum to 0 (additive identity)
14      
15        # Extract each digit from right to left
16        while n > 0:
17            # Get the last digit using divmod
18            # divmod(n, 10) returns (quotient, remainder)
19            n, digit = divmod(n, 10)
20          
21            # Update product by multiplying with current digit
22            product *= digit
23          
24            # Update sum by adding current digit
25            digit_sum += digit
26      
27        # Return the difference between product and sum
28        return product - digit_sum
29
1class Solution {
2    /**
3     * Calculates the difference between the product of digits and the sum of digits of an integer.
4     * 
5     * @param n The input positive integer
6     * @return The difference between product and sum of all digits
7     */
8    public int subtractProductAndSum(int n) {
9        int product = 1;  // Initialize product to 1 (multiplicative identity)
10        int sum = 0;      // Initialize sum to 0 (additive identity)
11      
12        // Process each digit from right to left
13        while (n > 0) {
14            int digit = n % 10;  // Extract the rightmost digit
15            product *= digit;    // Multiply digit to running product
16            sum += digit;        // Add digit to running sum
17            n /= 10;            // Remove the rightmost digit
18        }
19      
20        // Return the difference between product and sum
21        return product - sum;
22    }
23}
24
1class Solution {
2public:
3    int subtractProductAndSum(int n) {
4        int product = 1;  // Initialize product to 1 (multiplicative identity)
5        int sum = 0;      // Initialize sum to 0 (additive identity)
6      
7        // Extract each digit from right to left
8        while (n > 0) {
9            int digit = n % 10;  // Get the rightmost digit
10            product *= digit;    // Multiply digit to running product
11            sum += digit;        // Add digit to running sum
12            n /= 10;            // Remove the rightmost digit
13        }
14      
15        // Return the difference between product and sum
16        return product - sum;
17    }
18};
19
1/**
2 * Calculates the difference between the product of digits and sum of digits of a number
3 * @param n - The input non-negative integer
4 * @returns The difference between product and sum of digits
5 */
6function subtractProductAndSum(n: number): number {
7    // Initialize product of digits to 1 and sum of digits to 0
8    let productOfDigits: number = 1;
9    let sumOfDigits: number = 0;
10  
11    // Extract each digit from right to left
12    while (n > 0) {
13        // Get the rightmost digit
14        const currentDigit: number = n % 10;
15      
16        // Update product and sum with current digit
17        productOfDigits *= currentDigit;
18        sumOfDigits += currentDigit;
19      
20        // Remove the rightmost digit
21        n = Math.floor(n / 10);
22    }
23  
24    // Return the difference between product and sum
25    return productOfDigits - sumOfDigits;
26}
27

Time and Space Complexity

The time complexity is O(log n), where n is the given integer. This is because the while loop iterates once for each digit in the number. The number of digits in an integer n is floor(log₁₀(n)) + 1, which is O(log n). In each iteration, we perform constant time operations: integer division (divmod), multiplication, and addition.

The space complexity is O(1). The algorithm only uses a fixed amount of extra space regardless of the input size. We maintain two variables x and y to store the product and sum respectively, and one temporary variable v to store the current digit. These variables don't grow with the input size, resulting in constant space usage.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Not Handling Edge Case of n = 0

The most common pitfall is forgetting that when n = 0, the loop never executes, leaving product = 1 and digit_sum = 0, resulting in an incorrect answer of 1 - 0 = 1. However, the correct answer should be 0 - 0 = 0 since the only digit is 0.

Solution: Add a special case check at the beginning:

if n == 0:
    return 0

2. Integer Overflow in Other Languages

While Python handles arbitrary-precision integers automatically, implementing this in languages like C++ or Java could cause overflow when calculating the product for large numbers with many digits.

Solution:

  • Use appropriate data types (e.g., long long in C++ or long in Java)
  • Consider checking for overflow conditions
  • Add constraints validation based on the problem's input range

3. Incorrect Initial Values

A frequent mistake is initializing both variables to 0:

product = 0  # Wrong! This will always result in 0
digit_sum = 0

This causes the product to always be 0 regardless of the digits.

Solution: Always initialize:

  • Product to 1 (multiplicative identity)
  • Sum to 0 (additive identity)

4. Using String Conversion Inefficiently

Some developers might convert the number to a string first:

digits = [int(d) for d in str(n)]
product = 1
for d in digits:
    product *= d
return product - sum(digits)

While this works, it's less efficient due to string conversion overhead and additional memory usage.

Solution: Stick with the mathematical approach using modulo and division operations, which is more memory-efficient and typically faster.

5. Modifying the Original Input

If the original value of n needs to be preserved for other operations (in a larger context), directly modifying it in the loop could cause issues.

Solution: Create a copy if needed:

temp = n
while temp > 0:
    temp, digit = divmod(temp, 10)
    # ... rest of the logic
Discover Your Strengths and Weaknesses: Take Our 3-Minute Quiz to Tailor Your Study Plan:

Which of the following is a good use case for backtracking?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More