Given an integer number n, return the difference between the product of its digits and the sum of its digits.
給定整數(shù)n田篇,返回其數(shù)字乘積與數(shù)字總和之間的差。
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
Solution1:
class Solution:
def subtractProductAndSum(self, n: int) -> int:
n_prod = 1
n_sum = 0
while n:
digit = n % 10
n = n // 10
n_prod = n_prod * digit
n_sum = n_sum + digit
return n_prod - n_sum
Solution2:
class Solution:
def subtractProductAndSum(self, n: int) -> int:
n_prod, n_sum = 1, 0
str_n = str(n)
for i in str_n:
n_prod *= int(i)
n_sum += int(i)
return n_prod - n_sum
Both solutions here are very straightforward. One uses modulus and the other one use string