LeetCode 1281. Subtract the Prod

2020-12-03  本文已影响0人  LiNGYu_NiverSe

Given an integer number n, return the difference between the product of its digits and the sum of its digits.
给定整数n,返回其数字乘积与数字总和之间的差。

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:

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

上一篇 下一篇

猜你喜欢

热点阅读