Back to photostream

Subtract the Product and Sum of Digits of an Integer Leetcode Solution

Problem Statement

In this problem, we need to find the difference between the product of digits and the sum of digits of a given positive integer.

Example

1234

14

Explanation: Product = 4 * 3 * 2 * 1 = 24 and Sum = 4 + 3 + 2 + 1 = 10. So, the difference is 14

2045

-11

Explanation: Product = 2 * 0 * 4 * 5 = 0 and Sum = 2 + 0 + 4 + 5 = 11. So, the difference is -11.

Approach

It becomes easy to return the desired output if we could extract out the digits from the integer one by one. This can be easily done by using the '%' operator, as " % 10 " fetchs us the last digit of an integer, we can then divide the integer by 10 to pop the last digit out of it(as we did it in this problem). In this way, we can process each digit and find the product and the sum. Then, we can return the difference between them to get the required result.

 

Algorithm

 

- Initialize two variables, product = 1 and sum = 0 to store the product and sum of digits of integer N respectively

- Follow these steps until N > 0:

 

- Multiply the last digit of N to product, product *= N % 10

- Add the last digit of N to sum, sum += N % 10

- Divide N by 10 to drop the last digit, N /= 10

 

- Return product - sum

 

Implementation of Subtract the Product and Sum of Digits of an Integer Leetcode Solution

C++ Program

#includ

 

www.tutorialcup.com/leetcode-solutions/subtract-the-produ...

12 views
0 faves
0 comments
Uploaded on September 15, 2021