Subtract the Product and Sum of Digits of an Integer

Subtract the Product and Sum of Digits of an Integer

Leetcode Problem No : 1281

Refer to the problem statement.

Algorithm: Let p be the Integer.

  • Step 1: Declare 3 variables i.e. sum = 0, prod = 1, temp.

  • Step 2: If p > 0 then go to Step 3 else go to Step 7.

  • Step 3: Extract the last digit of p i.e. temp = p%10.

  • Step 4: Add the 'temp' variable to 'sum' i.e. sum = sum + temp.

  • Step 5: Multiple the 'variable' to 'prod' i.e. prod = prod * temp.

  • Step 6: Remove the last digit from n i.e. p = p/10. Goto Step 2.

  • Step 7: Return (prod-sum).

Examples:

Let p = 234

Step 1: sum = 0, prod = 1, temp

  • Iteration 1:

    Step 2: 234 > 0 then go to Step 3

    Step 3: temp = (234)%(10) = 4

    Step 4: sum = 0 + 4 = 4

    Step 5: prod = 1*4 = 4

    Step 6: p = (234)/(10) = 23

  • Iteration 2:

    Step 2: 23 > 0 then go to Step 3

    Step 3: temp = (23)%(10) = 3

    Step 4: sum = 4 + 3 = 7

    Step 5: prod = 4*3 = 12

    Step 6: p = (23)/(10) = 2

  • Iteration 3:

    Step 2: 2 > 0 then go to Step 3

    Step 3: temp = (2)%(10) = 2

    Step 4: sum = 7 + 2 = 9

    Step 5: prod = 12*2 = 24

    Step 6: p = (2)/(10) = 0

  • Iteration 4:

    Step 2: 0 not greater than 0. goto Step 7

Step 7: Return (24-9) = 15

Time Complexity: O(n) where n is the number of digits in the integer p.

Code: Java