Leetcode 1281: Subtract the Product and Sum of Digits of an Integer

Subtract the Product and Sum of Digits of an Integer

Category : Easy

Problem

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

https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/

Examples

Example 1:

Example 2:

Constraints

  • 1 <= n <= 10^5

Solution Approach

In this question, you just need to find the sum and product of the digits of a given number subtract it and return the difference. The only trivial thing in this question is to separate the digits and find the sum and product using those.

To solve this question we need to initialise 2 variables sum as 0 and product as 1 and we will store the sum and product in those respective variables. To separate the digits we run a loop where we take out the last digit by using the mod operation with 10. Then we multiply the digit to the product and add it to the sum variables. At the end of the loop, we decrease the number by removing its last digit. As the question requires I return product-sum as the answer.

Solution code

For more Leetcode explained solutions visit Leetcode Solutions.

If you like capture the flag challenges visit here.

Check out my socials below in the footer. Feel free to ask any doubts in the comment section or contact me via Contact page I will surely respond. Happy Leetcoding 

Leave a Comment

Your email address will not be published. Required fields are marked *