Subtract the Product and Sum of Digits of an Integer
The problem requires calculating the difference between the product of the digits of an integer n
and the sum of its digits. Here’s a simple Python solution for this problem:
|
|
Explanation
Initialization: We initialize
product
as 1 andsum_of_digits
as 0. These variables will hold the product and sum of the digits ofn
, respectively.Extracting Digits: We use a
while
loop to iterate through each digit ofn
. Inside the loop, we calculatedigit
asn % 10
, which gives us the rightmost digit ofn
.Calculating Product and Sum: We then multiply
product
bydigit
and adddigit
tosum_of_digits
.Updating n: We divide
n
by 10 (usingn //= 10
) to remove the rightmost digit, and continue the loop.Returning the Result: After the loop, we return the difference between
product
andsum_of_digits
, as required by the problem statement.
title: Subtract the Product and Sum of Digits of an Integer excerpt: This covers the basic building blocks such as reducing the input value by chopping the rightmost digit, extract the rightmost digit by modulo with 10 and chopping the rightmost digit by integer division with 10. tags: extract-rightmost-digit reducing-input-value modulo-operator integer-division chop-rightmost-digit
Given an integer number n, return the difference between the product of its digits and the sum of its digits.
Example 1:
Input: n = 234
Output: 15
Explanation:
Product of digits = 2 * 3 * 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15
Example 2:
Input: n = 4421
Output: 21
Explanation:
Product of digits = 4 * 4 * 2 * 1 = 32
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32 - 11 = 21
Constraints
- 1 <= n <= 10^5
Hints
- How to compute all digits of the number?
- Use modulus operator (%) to compute the last digit.
- Generalise modulus operator idea to compute all digits.
|
|
Building Blocks
- Reducing the Input Value by Chopping the Rightmost Digit
- Extract the Rightmost Digit by Modulo with 10
- Chopping the Rightmost Digit by Integer Division with 10