Given an integer number n
, return the difference between the product of its digits and the sum of its digits.
n
(e.g., the range of n
)?
n
to be a non-negative integer within the typical integer range.0
or single-digit numbers?
0
, the product and sum will both be 0
, so the result should be 0
.0
.No additional clarifications seem necessary. Let’s proceed with the solution.
n
to a string to easily iterate through each digit.def subtractProductAndSum(n: int) -> int:
digits = [int(digit) for digit in str(n)] # Convert number to list of digits
product = 1
total_sum = 0
for digit in digits:
product *= digit
total_sum += digit
return product - total_sum
# Example usage
print(subtractProductAndSum(234)) # Output: 15 (2*3*4 - (2+3+4) = 24 - 9 = 15)
print(subtractProductAndSum(4421)) # Output: 21 (4*4*2*1 - (4+4+2+1) = 32 - 11 = 21)
d
is the number of digits in the integer n
. This is because we iterate over each digit exactly once.n
to a string and list comprehension both operate in O(d) time.This completes the solution, ensuring efficiency and correctness based on the problem constraints and requirements.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?