잡다한 IT 지식

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

알고리즘 문제 풀이

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

가나무마 2021. 5. 25. 22:35

숫자 각 자릿수에 곱과 합을 빼서 리턴해주는 문제.
10으로 나눈 나머지가 1의 자릿수의 값이 됨.
0이 될 때까지 계속 반복하면 모든 자릿수를 거쳐갈 수 있음.

[내가 짠 코드]

class Solution {
    public int subtractProductAndSum(int n) {
        int number = n;

        int multilSum = 1;
        int sum = 0;
        while (number > 0) {
            int temp = number % 10;
            sum += temp;
            multilSum *= temp;

            number /= 10;
        }

        return multilSum- sum;
    }
}