Subtract the Product and Sum of Digits of an Integer (LeetCode)

1281. Subtract the Product and Sum of Digits of an Integer (Easy)

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

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

Hints:

How to compute all digits of the number?

Use modulus operator (%) to compute the last digit.

Generalize modulus operator idea to compute all digits.

Subtract the Product and Sum of Digits of an Integer

Subtract the Product and Sum of Digits of an Integer (Java)

class Solution {
    public int subtractProductAndSum(int n) {
        int product_of_digits=1;
        int sum_of_digits=0;
        while(n>0)
        {
            int rem = n%10;
            n = n/10;
            product_of_digits = product_of_digits*rem;
            sum_of_digits = sum_of_digits+rem;
        }
        int result = product_of_digits-sum_of_digits;
        return result;
    }
}

Dry Run:

let’s n = 234

product_of_digits = 1, sum_of_digits = 0

234>0 then go inside while loop
rem = 234%10 = 4
n = n/10 = 234/10 = 23
product_of_digits = product_of_digits*rem = 1*4 = 4
sum_of_digits = sum_of_digits+rem = 0+4 = 4

23>0 then go inside while loop
rem = 23%10 = 3
n = n/10 = 23/10 = 2
product_of_digits = product_of_digits*rem = 4*3 = 12
sum_of_digits = sum_of_digits+rem = 4+3 = 7

2>0 then go inside while loop
rem = 2%10 = 2
n = n/10 = 2/10 = 0
product_of_digits = product_of_digits*rem = 12*2 = 24
sum_of_digits = sum_of_digits+rem = 7+2 = 9

0>0 false

int result = product_of_digits-sum_of_digits = 24 – 9 = 15

Leave a Comment