본문 바로가기

Algorithms

leetcode 1281번 문제풀이

 

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

 

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

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

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

 

 

    public int subtractProductAndSum(int n) {
    	// 입력받은 숫자 n을 String으로 변환
        String numToStr = Integer.toString(n);
        Stack stack = new Stack();
        
        // String으로 변환한 numToStr의 문자를 하나씩 배열로 추출해 스택에 넣음.
        for(char c : numToStr.toCharArray()) {
            stack.push(Character.getNumericValue(c));
        }

        int multipleResult = 1;
        int sumResult = 0;
        while(!stack.isEmpty()) {
        // 스택에 하나씩 꺼내면서 num에 값 할당
            int num = (int)stack.pop();
            multipleResult *= num;
            sumResult += num;
        }

        return multipleResult - sumResult;
    }

 

제출

https://leetcode.com/submissions/detail/315831273/