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
This problem involves calculating the difference between the product and the sum of the digits of a given integer. The solution employs a straightforward iterative approach.
Approach:
Initialization: We initialize two variables: product
(to store the product of digits, starting at 1 to handle multiplication) and sum
(to store the sum of digits, starting at 0).
Iteration: We iterate through the digits of the integer. This is efficiently done using a loop and the modulo operator (%
) along with integer division (/
).
n % 10
).product
by multiplying it with the extracted digit.sum
by adding the extracted digit.n /= 10
or n = n / 10
).Return Value: Finally, we return the difference between the product
and the sum
.
Time Complexity Analysis:
The time complexity is O(log₁₀ n). The number of iterations in the loop is proportional to the number of digits in the input integer n
. The number of digits in n
is approximately log₁₀ n. Therefore, the algorithm's runtime grows logarithmically with the input size.
Space Complexity Analysis:
The space complexity is O(1). We use a constant number of variables regardless of the size of the input integer.
Code Examples in Multiple Languages:
Python:
def subtractProductAndSum(n: int) -> int:
product = 1
sum_digits = 0
while n > 0:
digit = n % 10
product *= digit
sum_digits += digit
n //= 10 # Integer division
return product - sum_digits
Java:
class Solution {
public int subtractProductAndSum(int n) {
int product = 1;
int sum = 0;
while (n > 0) {
int digit = n % 10;
product *= digit;
sum += digit;
n /= 10;
}
return product - sum;
}
}
C++:
class Solution {
public:
int subtractProductAndSum(int n) {
int product = 1;
int sum = 0;
while (n > 0) {
int digit = n % 10;
product *= digit;
sum += digit;
n /= 10;
}
return product - sum;
}
};
JavaScript:
const subtractProductAndSum = (n) => {
let product = 1;
let sum = 0;
while (n > 0) {
const digit = n % 10;
product *= digit;
sum += digit;
n = Math.floor(n / 10);
}
return product - sum;
};
Go:
func subtractProductAndSum(n int) int {
product := 1
sum := 0
for n > 0 {
digit := n % 10
product *= digit
sum += digit
n /= 10
}
return product - sum
}
These examples all follow the same algorithmic approach, differing only in syntax specific to each programming language. The core logic remains consistent across all implementations.