Problem

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

Examples

Example 1

1
2
3
4
5
6
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

1
2
3
4
5
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

  1. Initialize prod = 1 and s = 0.
  2. While n > 0, extract the last digit, multiply it to prod, and add it to s.
  3. Return prod - s.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
func subtractProductAndSum(n int) int {
    prod, s := 1, 0
    for n > 0 {
        d := n % 10
        prod *= d
        s += d
        n /= 10
    }
    return prod - s
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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
    }
}
1
2
3
4
5
6
7
8
9
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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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.