Subtract the Product and Sum of Digits of an Integer - Problem

Given an integer number n, return the difference between the product of its digits and the sum of its digits.

The product is calculated by multiplying all digits together, and the sum is calculated by adding all digits together.

For example, if n = 234, the product is 2 × 3 × 4 = 24 and the sum is 2 + 3 + 4 = 9, so the answer is 24 - 9 = 15.

Input & Output

Example 1 — Basic Three Digit Number
$ Input: n = 234
Output: 15
💡 Note: Product of digits: 2 × 3 × 4 = 24. Sum of digits: 2 + 3 + 4 = 9. Difference: 24 - 9 = 15
Example 2 — Single Digit Number
$ Input: n = 4
Output: 0
💡 Note: Product of digits: 4. Sum of digits: 4. Difference: 4 - 4 = 0
Example 3 — Number with Zero
$ Input: n = 4021
Output: -7
💡 Note: Product of digits: 4 × 0 × 2 × 1 = 0. Sum of digits: 4 + 0 + 2 + 1 = 7. Difference: 0 - 7 = -7

Constraints

  • 1 ≤ n ≤ 105

Visualization

Tap to expand
Subtract Product and Sum of Digits INPUT Integer n = 234 2 3 4 d1 d2 d3 Extract each digit using modulo (%) and division (/) digit = n % 10 n = n / 10 // repeat n = 234 ALGORITHM STEPS 1 Initialize product = 1, sum = 0 2 Loop through digits while n {'>'} 0 3 Update values product *= digit sum += digit 4 Return difference return product - sum Calculation Trace Digit Product Sum 4 1*4=4 0+4=4 3 4*3=12 4+3=7 2 12*2=24 7+2=9 Final: 24 9 FINAL RESULT Product of Digits 2 x 3 x 4 = 24 Sum of Digits 2 + 3 + 4 = 9 - Difference 24 - 9 = 15 Output: 15 [OK] Verified Key Insight: Single pass O(d) where d = number of digits. Extract digits using n % 10, then divide by 10. Accumulate product (multiply) and sum (add) simultaneously. No extra space needed - O(1). TutorialsPoint - Subtract the Product and Sum of Digits of an Integer | Single Pass Calculation
Asked in
Amazon 12 Microsoft 8
25.0K Views
Medium Frequency
~5 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen