본문 바로가기

알고리즘 풀이(JAVA)/leetcode

[leetcode] 1281. Subtract the Product and Sum of Digits of an Integer (java)

<문제 1281. Subtract the Product and Sum of Digits of an Integer>

[문제]

번역 :

[정수 n이 주어졌을 때, 그 자릿수의 곱과 자릿수의 합의 차이를 반환합니다.]

 

[답안]

class Solution {
    public int subtractProductAndSum(int n) {
        int Multiplication = 1; // 자릿수의 곱
        int sum = 0; // 자릿수의 합

        while (n != 0) {
            Multiplication *= n % 10;
            sum += n % 10;
            n = n / 10;
        }
        return Multiplication - sum;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int n = 234;
        int n2 = 4421;
        System.out.println(sol.subtractProductAndSum(n));
        System.out.println(sol.subtractProductAndSum(n2));
    }
}

출처

https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/description/

 

Subtract the Product and Sum of Digits of an Integer - LeetCode

Can you solve this real interview question? Subtract the Product and Sum of Digits of an Integer - 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 Explana

leetcode.com