무냐의 개발일지

1281. Subtract the Product and Sum of Digits of an Integer 본문

LeetCode 코딩테스트

1281. Subtract the Product and Sum of Digits of an Integer

무냐코드 2024. 4. 13. 23:34

👩‍💻 문제

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

 

 

💡 풀이 #1 (Basic)

class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        prod_n = 1
        sum_n = 0
        for digit in str(n):
            prod_n *= int(digit)
            sum_n += int(digit)
        return prod_n - sum_n

 

✍️ 해설 #1

int를 자릿수별로 분해해주기 위해 str으로 바꿨다가, 연산할때는 다시 int로 바꿔주는 꽤나 심플한 방법이다 !!! 

 

💡 풀이 #2 (Advanced)

class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        return abs(eval('*'.join(str(n))) - eval('+'.join(str(n))))

 

✍️ 해설 #2 

여기서 eval 함수를 사용하는 참신한 풀이를 생각해볼 수 있다 !!!

예를 들어, eval('3 + 5')를 호출하면, 이 문자열이 파이썬 코드로 실행되어 3과 5를 더한 결과인 8을 반환한다.

그러니까, n 을 str 형태로 만들어줘서 '+', '*' 으로 join만 해주고 eval을 씌워주면 되는거다.

 

a =123
print('*'.join(str(a)))

1*2*3

 

혹시 모르니 abs를 씌워준다 ㅎㅎ 

 
 

 

🥳 배운점

의외로 잠깐 헤맸는데, n = 123 형태의 숫자에서 각 digits을 어떻게 iterate하는지 몰랐다. str, int를 더 자유자재로 쓸 수 있을 것 같다. 

그리고 eval 함수를 기억하자 !!!