관리 메뉴

솜씨좋은장씨

[leetCode] 1281. Subtract the Product and Sum of Digits of an Integer (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 1281. Subtract the Product and Sum of Digits of an Integer (Python)

솜씨좋은장씨 2020. 8. 30. 01:27
728x90
반응형

Given an integer number n, return the difference between the product of its digits and the sum of its digits.

 

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

Solution

from functools import reduce

class Solution:
    @staticmethod
    def multiply(arr):
        return reduce(lambda x, y: x * y, arr)
    
    def subtractProductAndSum(self, n: int) -> int:
        string_n = list(str(n))
        
        n_numbers = list(map(int, string_n))
        
        if len(n_numbers) > 1:
            gopsam = self.multiply(n_numbers)
            arr_sum = sum(n_numbers)
        
            answer = gopsam - arr_sum
        else:
            answer = 0
        
        return answer

 

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments