[Leet Code] Subtract the Product and Sum of Digits of an Integer
2 min readDec 7, 2020
Leetcode: https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/
Problem:
Given an integer number n, return the difference between the product of its digits and the sum of its digits.
Example:
Input: n = 234
Output: 15
Explanation:
Product of digits = 2 * 3 * 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15
Solution:
class Solution(object):
def subtractProductAndSum(self, n):
"""
:type n: int
:rtype: int
"""
product_of_digits = 0
sum_of_digits = 0
list_of_nums = list(str(n))
for v,i in enumerate(list_of_nums):
if v == 0:
product_of_digits = int(i)
else:
product_of_digits = product_of_digits * int(i)
sum_of_digits = sum_of_digits + int(i)
return product_of_digits - sum_of_digits
Explanation:
Create two variables, one to hold the balues of the product of the digits, and the other for the sum of the digits. Then we turn the string of numbers into a list. If we enumerate the list of nums, then we can check if the first index is 0, then we need to make the product the first number, otherwise it would always multiple by 0 for the first number. Then after that we can do the product multiplied by itself. Same for the digit, then we just return the product_of_digits minus sum_of_digits.