Subtract the Product and Sum of Digits of an Integer

Problem Description

So, you think you can just take a number, multiply its digits together, add them up, and then subtract the sum from the product? Well, welcome to the world of “Subtract the Product and Sum of Digits of an Integer!” It’s like a math party where the digits of your number are the guests, and they’re all trying to outshine each other.

Imagine you have a number, say 234. You take the digits (2, 3, and 4), multiply them together to get 24, then you add them up to get 9. Finally, you subtract the sum from the product, and voilà! You’re left with 15. It’s like a math version of a reality show where only the best digits survive!

Code Solution


class Solution {
  public int subtractProductAndSum(int n) {
    int prod = 1;
    int summ = 0;

    for (; n > 0; n /= 10) {
      prod *= n % 10;
      summ += n % 10;
    }

    return prod - summ;
  }
}

Approach

The code provided takes an integer n and initializes two variables: prod for the product of the digits and summ for the sum of the digits. It then enters a loop that continues until n is reduced to 0. In each iteration, it extracts the last digit of n, updates the product and sum, and then removes the last digit from n. Finally, it returns the difference between the product and the sum.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(d), where d is the number of digits in the integer n.
Space Complexity O(1), as we are using a constant amount of space regardless of the input size.

Real-World Example

Let’s say you’re at a party, and you have a bag of candies. Each candy represents a digit of a number. You decide to multiply the number of candies you have (the product) and then add them up (the sum). After a while, you realize you have more candies than you can eat, so you decide to subtract the sum from the product to see how many candies you can actually enjoy. This is essentially what the problem is asking you to do with the digits of an integer!

Similar Problems

If you enjoyed this problem, you might also like these: