[leetcode] 8_1281

less than 1 minute read

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

Problem

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

Example

Input: n = 234
Output: 15
Explanation:
Product of digits = 2 * 3 * 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15

해석

입력된 숫자의 각 자리수 마다의 곱(1) 과 각 자리수 마다의 합(2)을 뺀 값 result를 반환한다.

Solution in JavaScript

/**
 * @param {number} n
 * @return {number}
 */
var subtractProductAndSum = function(n) {
    let product = 1;
    let sum=0;
    while(n>=1){
        let num=n%10;               //마지막자리수를 구함 10으로 나눈 나머지값이기때문에
        product*=num;
        sum+=num;
        n=Math.floor(n/10);         //javascript의 장점이자 단점.. 자료형타입이 따로없기때문에
                                    //n/10은 type을 따지지않기때문에 소수점을 버리기 위해 Math.floor을 활용
    }
    return product-sum;
};

Solution in Java

class Solution {
    public int subtractProductAndSum(int n) {
        int product=1;
        int sum=0;
        while(n!=0){
            sum+=n%10;
            product*=n%10;
            n=n/10;                           //Java는 type에 강한 언어 int를 int로 나누었기때문에 알아서 소수점을 없애버림

        }
        return product-sum;
    }
}

Updated: