1281. Subtract the Product and Sum of Digits of an Integer
Problem Description
Given an integer n
, the task is to find the difference between two quantities related to the digits of n
. These quantities are the product of all the digits of n
and the sum of all the digits of n
. To clarify, if n
is 234
, the product of its digits is 2 * 3 * 4
which equals 24
, and the sum of its digits is 2 + 3 + 4
which equals 9
. The result to return for the problem would be the product minus the sum, thus 24 - 9 = 15
.
Intuition
To solve this problem, we can simulate the process of extracting each digit of the number n
, and then perform the respective multiplication and addition operations with these digits.
Firstly, consider the need to handle each digit of the integer n
separately. A convenient way to extract the digits of an integer is by repeatedly dividing the number by 10
and taking the remainder, which gives us the last digit of the current number. In each iteration, we remove this last digit by performing integer division by 10
.
With each digit extracted, we can directly calculate two running totals: one for the product of the digits, and another for the sum of the digits.
- We initialize a variable (let's call it
x
) to1
to hold the product (since the product of zero is zero, which would nullify all subsequent multiplications). - We initialize another variable (let's call it
y
) to0
to hold the sum (since adding zero does not change the sum). - As we extract each digit
v
, we updatex
by multiplying it withv
(x = x * v
) and updatey
by addingv
to it (y = y + v
). - After we have finished processing all the digits of
n
, we calculate the difference between the product and the sum (x - y
) and return this as our result.
This approach allows us to keep track of both the product and the sum of the digits of n
in a single pass over the number, which is both efficient and straightforward.
Learn more about Math patterns.
Solution Approach
The solution follows a straightforward simulation approach. The goal is to iterate through each digit of the given number n
and calculate both the product and the sum of these digits. To make it possible, we employ a basic while
loop that continues to execute as long as the number n
is greater than 0.
Below are the steps outlining the implementation details and the logical flow of the program:
-
We start by initializing two variables:
x
with a value of1
to serve as the accumulator for the product, andy
with a value of0
to serve as the accumulator for the sum of the digits. -
We enter a
while
loop that will run untiln
becomes0
. -
Inside the loop, we utilize the
divmod
function, which performs both integer division and modulo operation in a single step. The statementn, v = divmod(n, 10)
dividesn
by10
, with the quotient assigned back ton
(essentially stripping off the last digit) and the remainder assigned tov
(which is the last digit of the currentn
). -
With the digit
v
isolated, we update our product variablex
by multiplying it byv
(sincex
keeps the running product of the digits). -
Similarly, we update our sum variable
y
by addingv
to it, keeping a running sum of the digits. -
After the loop has completed (all digits of
n
have been processed), the variablex
holds the product of the digits, and the variabley
holds the sum of the digits of the initialn
. -
Lastly, we return the difference between these two values,
x - y
.
This algorithm makes use of very basic operators and control structures in Python and does not require the use of any complex data structures or patterns. The simplicity of the algorithm—iterating over each digit, maintaining running totals for the product and sum, and then returning the difference—illustrates the power of a linear implementation that performs the required operations in a single pass over the digits of the input number.
Ready to land your dream job?
Unlock your dream job with a 2-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's illustrate the solution approach using the integer n = 523
.
- Initialize two variables:
x
as1
(for product) andy
as0
(for sum). - Begin a
while
loop;n
is523
, which is greater than0
, so we proceed. - Inside the loop, we apply
divmod
operation:n, v = divmod(523, 10)
which givesn = 52
andv = 3
. - Update
x
by multiplying it withv
:x = 1 * 3 = 3
. - Update
y
by addingv
:y = 0 + 3 = 3
. - Loop iterates again. Now
n
is52
. Applydivmod
:n, v = divmod(52, 10)
which givesn = 5
andv = 2
. - Update
x
:x = 3 * 2 = 6
. - Update
y
:y = 3 + 2 = 5
. - Loop iterates again. Now
n
is5
. Applydivmod
:n, v = divmod(5, 10)
which givesn = 0
andv = 5
(we have extracted the last digit). - Update
x
:x = 6 * 5 = 30
. - Update
y
:y = 5 + 5 = 10
. - Loop ends since
n
is now0
. - We now have
x = 30
andy = 10
. Calculate the difference:x - y = 30 - 10 = 20
. - The result is
20
, which is the difference between the product of523
's digits and the sum of523
's digits.
The walkthrough demonstrates the simple, yet effective, process of using a loop to tear down the number into its constituent digits, calculate the running product and sum, and finally determine the difference between these two quantities.
Solution Implementation
1class Solution:
2
3 def subtractProductAndSum(self, n: int) -> int:
4 # Initialize the product and sum variables
5 product_of_digits = 1 # Holds the product of the digits
6 sum_of_digits = 0 # Holds the sum of the digits
7
8 # Loop through each digit of the number
9 while n:
10 # Divmod returns the quotient and the remainder
11 # n becomes the quotient, and digit holds the remainder (current digit)
12 n, digit = divmod(n, 10)
13
14 # Multiply the current digit by the product
15 product_of_digits *= digit
16
17 # Add the current digit to the sum
18 sum_of_digits += digit
19
20 # Return the result of subtracting the sum from the product of digits
21 return product_of_digits - sum_of_digits
22
1class Solution {
2
3 // Function to subtract the product of digits from the sum of digits of an integer
4 public int subtractProductAndSum(int n) {
5 // Initializing product to 1 as we will multiply digits with it
6 int product = 1;
7 // Initializing sum to 0 as we will add digits to it
8 int sum = 0;
9
10 // Looping through each digit of the number
11 while (n > 0) {
12 // Getting the last digit of the number
13 int digit = n % 10;
14
15 // Multiplying the current digit with the product
16 product *= digit;
17 // Adding the current digit to the sum
18 sum += digit;
19
20 // Removing the last digit from n
21 n /= 10;
22 }
23 // Returning the difference between the product and the sum
24 return product - sum;
25 }
26}
27
1class Solution {
2public:
3 int subtractProductAndSum(int n) {
4 int product = 1; // Initialize product to 1 since we are multiplying
5 int sum = 0; // Initialize sum to 0 since we are adding
6
7 // Loop through each digit of the number
8 while (n > 0) {
9 int digit = n % 10; // Get the last digit
10 product *= digit; // Multiply the digit to the product
11 sum += digit; // Add the digit to the sum
12 n /= 10; // Remove the last digit from the number
13 }
14
15 // Return the difference between the product and sum of digits
16 return product - sum;
17 }
18};
19
1// Function to calculate and return the difference between the product
2// of digits and the sum of digits of the given number.
3function subtractProductAndSum(n: number): number {
4 // Initialize product to 1 and sum to 0
5 let product = 1;
6 let sum = 0;
7
8 // Loop to process each digit in the number
9 while (n > 0) {
10 // Extract the last digit using modulo operation
11 const digit = n % 10;
12
13 // Multiply the product by the digit
14 product *= digit;
15
16 // Add the digit to the sum
17 sum += digit;
18
19 // Remove the last digit by dividing by 10 and flooring the result
20 // to get an integer for the next iteration
21 n = Math.floor(n / 10);
22 }
23
24 // Return the difference between product and sum
25 return product - sum;
26}
27
Time and Space Complexity
The time complexity of the given code is O(log n)
where n
is the input integer. This is because the while loop runs once for each digit of n
, and the number of digits in n
is proportional to the logarithm of n
.
The space complexity of the code is O(1)
. This is constant space complexity because the algorithm only uses a fixed amount of additional space (variables x
and y
, and temporary variables for intermediate calculations like n
and v
) that does not scale with the input size n
.
Learn more about how to find time and space complexity quickly using problem constraints.
How many times is a tree node visited in a depth first search?
Recommended Readings
Math for Technical Interviews How much math do I need to know for technical interviews The short answer is about high school level math Computer science is often associated with math and some universities even place their computer science department under the math faculty However the reality is that you
LeetCode Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way we
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https algomonster s3 us east 2 amazonaws com recursion jpg You first
Want a Structured Path to Master System Design Too? Don’t Miss This!