leetCode

[Easy] 1281. Subtract the Product and Sum of Digits of an Integer

개발자 자두 2022. 5. 26. 11:53

문제

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

 

풀이 과정

  • 곱셈을 계산할 mul과 합을 계산할 plus 변수를 초기화한다.
  • n > 0일 때까지 while문을 돈다
    • n % 10 계산을 하면 문자열에서 charAt() 한 것처럼 한 자리수씩 값을 비교할 수 있다. 1의 자릿수부터 num으로 가져온다.
    • mul과 plus에 각각 계산을 한다.
    • num / 10을 하면 다음 자리수로 이동한다. 이때, parseInt를 해주어야 소수점을 제외한 정확한 계산이 가능하다. 
  • while문을 다 돌고 나면 mul - plus 값을 반환한다.

 

풀이 코드

/**
 * @param {number} n
 * @return {number}
 */
var subtractProductAndSum = function(n) {
    let mul = 1;
    let plus = 0;
    
    while(n > 0){
        let num = n % 10;
        
        mul *= num;
        plus += num;

        n = parseInt(n / 10);
    }
    
    return mul - plus;
};