Subtract the Product and Sum of Digits of an Integer Solution
Subtract the Product and Sum of Digits of an Integer solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript.
Subtract the Product and Sum of Digits of an Integer is an easy coding problem on math, asked in Amazon, Infosys and Wipro interviews.
- Difficulty: Easy
- Topics: Math
- Asked at: Amazon, Infosys, Wipro
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given an integer n, return the product of its digits minus the sum of its digits.
Example 1
Input: n = 234
Output: 15
Explanation: Product = 2 × 3 × 4 = 24, sum = 2 + 3 + 4 = 9, and 24 - 9 = 15.
Example 2
Input: n = 4421
Output: 21
Explanation: Product = 32, sum = 11.
Example 3
Input: n = 1
Output: 0
Constraints
1 <= n <= 100000
Hints for Subtract the Product and Sum of Digits of an Integer
Hint 1
One pass over the digits can maintain both accumulators at once.
Hint 2
Seed the product at 1 and the sum at 0.
Hint 3
A zero digit legitimately zeroes the product — do not skip it.
How to solve Subtract the Product and Sum of Digits of an Integer
One digit-peeling loop maintains both accumulators — the product seeded at 1 and the sum at 0 — then return their difference.
Approach
- Set
prod = 1,total = 0. - While
n > 0:d = n % 10; multiplyprodbyd, adddtototal,n //= 10. - Return
prod - total.
Why it works
Both quantities are simple folds over the digit sequence and can share the traversal.
Complexity
- Time —
O(digits) - Space —
O(1)
Pitfalls
- A zero digit legitimately zeroes the product; do not skip it.
- Seeding the product at 0 makes every answer
-sum.
Reference solution
Python
def subtractProductAndSum(n: int) -> int:
prod, total = 1, 0
while n > 0:
d = n % 10
prod *= d
total += d
n //= 10
return prod - totalJava
public static int subtractProductAndSum(int n) {
int prod = 1, total = 0;
while (n > 0) {
int d = n % 10;
prod *= d;
total += d;
n /= 10;
}
return prod - total;
}C++
int subtractProductAndSum(int n) {
int prod = 1, total = 0;
while (n > 0) {
int d = n % 10;
prod *= d;
total += d;
n /= 10;
}
return prod - total;
}JavaScript
var subtractProductAndSum = function(n) {
let prod = 1, total = 0;
while (n > 0) {
const d = n % 10;
prod *= d;
total += d;
n = Math.floor(n / 10);
}
return prod - total;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.