#1281
Subtract the Product and Sum of Digits of an Integer
Easy Digit extraction
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Return (product of the digits) minus (sum of the digits) of a positive integer.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: multiply the digits, add the digits, and subtract.
Why this works: % 10 reads the last digit and / 10 removes it. Product starts at 1, sum at 0.
Example: n = 234
digit 4: product 4, sum 4digit 3: product 12, sum 7digit 2: product 24, sum 924 - 9 = 15
✦Hints open one at a time
n % 10 gives the last digit, n / 10 removes it.
Start the product at 1 and the sum at 0.
↗Approach
Extract digits one by one, updating the product and the sum, then subtract.
</>Solution (Java)
class Solution {
public int subtractProductAndSum(int n) {
int product = 1, sum = 0;
while (n > 0) {
int d = n % 10;
product *= d;
sum += d;
n /= 10;
}
return product - sum;
}
}
!Common mistake
Starting the product at 0, which makes it 0 forever.
Complexity
- Time: O(log10 n).
- Space: O(1).
