DEV Community

Cover image for Algorithms Problem Solving: Subtract product and sum
TK
TK

Posted on • Originally published at leandrotk.github.io

3 1

Algorithms Problem Solving: Subtract product and sum

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Resources

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay