Python Beginner Algorithms Tutorial
Subtract the Product and Sum of Digits of an Integer (via Leetcode)
- March 28, 2020
- Key Terms: functions, loops
Problem setup:
This problem can be found on Leetcode.
Given an integer number n
, return the difference between the product of its digits and the sum of its digits.
Test Cases¶
In [3]:
# assert subtract_product_and_sum(35) == 27
- Product of digits = 3 * 5 = 35
- Sum of digits = 3 + 5 = 8
- Difference = 35 - 8 = 27
In [2]:
# assert subtract_product_and_sum(235) == 20
- Product of digits = 2 3 5 = 30
- Sum of digits = 2 + 3 + 5 = 10
- Difference = 30 - 10 = 20
Pseudocode¶
In [ ]:
# define function to with argument for num
# cast num to a string to be able to iterate over its digits
# assign variable to hold product of digits as 1
# assign variable to hold sum of digits as 0
# iterate over each digit in string version of number:
# cast string digit to an integer
# product of digits = product of digits * integer digit
# sum of digits = sum of digits * integer digit
# assign variable difference to be product of digits minus sum of digits
# return difference
My solution above is the simplest possible solution. I wouldn't dwell on space and time complexity here. There's minimal space used as only 3 variables are created (no data structures). For time complexity, the simplest possible operation is done which is a single iteration over each digit in the input integer.
Code¶
In [1]:
def subtract_product_and_sum(n)
str_n = str(n)
product_of_digits = 1
sum_of_digits = 0
for number in str_n:
int_n = int(number)
product_of_digits *= int_n
sum_of_digits += int_n
diff = product_of_digits - sum_of_digits
return diff
Verify test cases¶
In [ ]:
assert subtract_product_and_sum(35) == 27
In [ ]:
assert subtract_product_and_sum(235) == 20