This post is part of the Algorithms Problem Solving series.
Problem Description
This is the Subtract Product and Sum problem. The description looks like this:
Given an integer number n, return the difference between the product of its digits and the sum of its digits.
Examples
Input: n = 234
Output: 15
Input: n = 4421
Output: 21
Solution
For each character, we transform it into an integer value, and then use as part of the multiplication and sum. At the top of the function scope, we define two variables: one for the multiplications and the other for the additions.
After the loop, we just need to return the subtraction between multiplications and additions.
def subtract_product_and_sum(num):
multiplications = 1
additions = 0
for digit in str(num):
multiplications *= int(digit)
additions += int(digit)
return multiplications - additions
Resources
- Learning Python: From Zero to Hero
- Algorithms Problem Solving Series
- Big-O Notation For Coding Interviews and Beyond
- Learn Python from Scratch
- Learn Object-Oriented Programming in Python
- Data Structures in Python: An Interview Refresher
- Data Structures and Algorithms in Python
- Data Structures for Coding Interviews in Python
- One Month Python Course
Top comments (0)