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^5To solve #1281 Subtract the Product and Sum of Digits of an Integer, the key idea is to process each digit of the given integer individually. You can repeatedly extract the last digit using the modulus (%) operation and remove it using integer division / 10. While iterating through the digits, maintain two running values: one for the product of digits and another for their sum.
For every extracted digit, update the product by multiplying it with the current digit and update the sum by adding the digit. After all digits have been processed, compute the final result by subtracting the total sum from the total product.
This approach is efficient because each digit is visited exactly once. The time complexity depends on the number of digits in the integer, making it proportional to log10(n). The algorithm also uses only a few variables, so the space usage remains constant.
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Digit Extraction using Modulus and Division | O(d) where d is the number of digits (≈ log10(n)) | O(1) |
Fisher Coder
Use these hints if you're stuck. Try solving on your own first.
How to compute all digits of the number ?
Use modulus operator (%) to compute the last digit.
Generalise modulus operator idea to compute all digits.
Watch expert explanations and walkthroughs
Practice problems asked by these companies to ace your technical interviews.
Explore More ProblemsJot down your thoughts, approach, and key learnings
Yes, this type of problem is common in coding interviews, especially for beginners. It tests understanding of basic arithmetic operations, digit manipulation, and control flow.
No special data structure is required for this problem. Simple integer variables are sufficient to keep track of the running product and sum while extracting digits from the number.
The optimal approach is to iterate through each digit of the number using modulus and division operations. Maintain two variables to track the product and sum of the digits, then return their difference at the end.
The time complexity is O(d), where d is the number of digits in the integer. Since the number of digits is roughly log10(n), the algorithm is very efficient even for large numbers.