algoadvance

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

Problem Statement

Leetcode Problem 1281: “Subtract the Product and Sum of Digits of an Integer”

Given an integer number n, the task is to:

  1. Calculate the product of its digits.
  2. Calculate the sum of its digits.
  3. Return the difference between the product of its digits and the sum of its digits.

Example:

Input: n = 234
Output: 15 
Explanation: 
Product of digits = 2 * 3 * 4 = 24 
Sum of digits = 2 + 3 + 4 = 9 
Result = 24 - 9 = 15

Clarifying Questions

  1. Q: What is the range of the input integer n? A: We assume n is a positive integer as the problem domain usually deals with positive integers unless otherwise specified.

  2. Q: Can the input integer n be a single digit? A: Yes, though in such cases the product and sum would be the same, resulting in a difference of 0.

Code

#include <iostream>

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;
    }
};

int main() {
    Solution solution;
    int n = 234; // example input
    std::cout << "Result: " << solution.subtractProductAndSum(n) << std::endl;
    return 0;
}

Strategy

  1. Initialize Variables:
    • product to 1 (as multiplying by 1 has no effect).
    • sum to 0 (as adding 0 has no effect).
  2. Iterate Through Digits:
    • Use a loop to process each digit of n.
    • Extract the last digit using modulo operation (n % 10).
    • Add this digit to sum.
    • Multiply this digit with product.
    • Remove the last digit by performing integer division by 10 (n /= 10).
  3. Calculate and Return Result:
    • Subtract sum from product and return the result.

Time Complexity

This solution efficiently processes each digit of the number and computes the desired result in a linear time relative to the number of digits.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI