LeetCode 1281. Subtract the Product and Sum of Digits of an Integer 减去整数位数的乘积和和 (Easy)

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。