美文网首页
LeetCode 1281. Subtract the Prod

LeetCode 1281. Subtract the Prod

作者: LiNGYu_NiverSe | 来源:发表于2020-12-03 04:26 被阅读0次

    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:

    • 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

    相关文章

      网友评论

          本文标题:LeetCode 1281. Subtract the Prod

          本文链接:https://www.haomeiwen.com/subject/gpvpwktx.html