Algorithms Problem Solving: Subtract product and sum

·

0 min read

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