Similar Problems

Similar Problems not available

Subtract The Product And Sum Of Digits Of An Integer - Leetcode Solution

Companies:

LeetCode:  Subtract The Product And Sum Of Digits Of An Integer Leetcode Solution

Difficulty: Easy

Topics: math  

Problem Statement:

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

Example 1:

Input: n = 234 Output: 15 Explanation: Product of digits = 2 * 3 * 4 = 24 Sum of digits = 2 + 3 + 4 = 9 Result = 24 - 9 = 15

Example 2:

Input: n = 4421 Output: 21 Explanation: Product of digits = 4 * 4 * 2 * 1 = 32 Sum of digits = 4 + 4 + 2 + 1 = 11 Result = 32 - 11 = 21

Solution:

We can solve this problem by breaking down the integer into its digits. We can then calculate the product and sum of the digits and subtract them to get the result.

Algorithm:

  1. Initialize two variables, product and sum, to 1 and 0 respectively.
  2. Convert the integer n to a string so that we can access each digit using string indexing.
  3. Loop through each character in the string representation of the number. a. Convert the character to an integer using the int() method. b. Multiply the integer by the current value of the product variable. c. Add the integer to the current value of the sum variable.
  4. Subtract the sum from the product and return the result.

Python Code:

class Solution: def subtractProductAndSum(self, n: int) -> int: # Initialize product and sum variables product, sum = 1, 0 # Convert the integer to a string s = str(n) # Loop through each character in the string representation of the number for ch in s: # Convert the character to an integer digit = int(ch) # Update the product and sum variables product *= digit sum += digit # Return the difference between the product and sum return product - sum

Time Complexity:

The time complexity of this solution is O(n), where n is the number of digits in the integer n.

Space Complexity:

The space complexity of this solution is O(1), since we are only using a constant amount of extra space to store the product and sum variables.

Subtract The Product And Sum Of Digits Of An Integer Solution Code

1