Subtract the Product and Sum of Digits of an Integer
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given an integer number n, return the difference between the product of its digits and the sum of its digits.
Examples
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^5
Solution
Method 1 – Digit Extraction
Intuition
Extract each digit of the number, compute the product and sum, and return their difference. This is a direct and efficient approach for small numbers.
Approach
- Initialize
prod = 1ands = 0. - While
n > 0, extract the last digit, multiply it toprod, and add it tos. - Return
prod - s.
Code
C++
class Solution {
public:
int subtractProductAndSum(int n) {
int prod = 1, s = 0;
while (n > 0) {
int d = n % 10;
prod *= d;
s += d;
n /= 10;
}
return prod - s;
}
};
Go
func subtractProductAndSum(n int) int {
prod, s := 1, 0
for n > 0 {
d := n % 10
prod *= d
s += d
n /= 10
}
return prod - s
}
Java
class Solution {
public int subtractProductAndSum(int n) {
int prod = 1, s = 0;
while (n > 0) {
int d = n % 10;
prod *= d;
s += d;
n /= 10;
}
return prod - s;
}
}
Kotlin
class Solution {
fun subtractProductAndSum(n: Int): Int {
var num = n
var prod = 1
var s = 0
while (num > 0) {
val d = num % 10
prod *= d
s += d
num /= 10
}
return prod - s
}
}
Python
class Solution:
def subtractProductAndSum(self, n: int) -> int:
prod, s = 1, 0
while n > 0:
d = n % 10
prod *= d
s += d
n //= 10
return prod - s
Rust
impl Solution {
pub fn subtract_product_and_sum(mut n: i32) -> i32 {
let mut prod = 1;
let mut s = 0;
while n > 0 {
let d = n % 10;
prod *= d;
s += d;
n /= 10;
}
prod - s
}
}
TypeScript
class Solution {
subtractProductAndSum(n: number): number {
let prod = 1, s = 0;
while (n > 0) {
const d = n % 10;
prod *= d;
s += d;
n = Math.floor(n / 10);
}
return prod - s;
}
}
Complexity
- ⏰ Time complexity:
O(log n)— Each digit is processed once. - 🧺 Space complexity:
O(1)— Only a few variables are used.