algoadvance

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

Problem Statement

You are given an integer n. Return the difference between the product of its digits and the sum of its digits.

Clarifying Questions

  1. Constraints:
    • What is the range of the integer n?
      • The problem usually specifies that n is a positive integer, typically constrained by the input limits of the platform.
  2. Edge Cases:
    • What should be returned if n has only one digit?
      • If n has only one digit, the product and the sum of that digit will be the same, and their difference will be zero.

Strategy

  1. Initialize Variables:
    • Initialize product to 1 and sum to 0.
  2. Process Each Digit:
    • While n is greater than 0:
      • Extract the last digit using n % 10.
      • Update the product by multiplying it by the extracted digit.
      • Update the sum by adding the extracted digit.
      • Remove the last digit from n using integer division n = n / 10.
  3. Calculate Result:
    • Return the difference between product and sum.

Code

public class Solution {
    public int subtractProductAndSum(int n) {
        int product = 1;
        int sum = 0;
        
        while (n > 0) {
            int digit = n % 10;
            product *= digit;
            sum += digit;
            n /= 10;
        }
        
        return product - sum;
    }
}

Time Complexity

The time complexity of the solution is O(d), where d is the number of digits in the integer n. This is because each digit is processed exactly once.

Example

Let’s walk through an example for better understanding:

  1. Input: n = 234
    • Digits: 2, 3, 4
    • Product: (2 \times 3 \times 4 = 24)
    • Sum: (2 + 3 + 4 = 9)
    • Result: (24 - 9 = 15)

The function returns 15 as expected.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI