알고리즘/해결

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

언클린 2020. 1. 13. 00:44
728x90

1.문제(원본)

  • 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

2.문제

특정 숫자를 넣어 10^n의 각각의 숫자의 곱과 각각의 숫자의 합을 뺀 수를 구하라.

 

3.나의 생각

class Solution {

    func subtractProductAndSum(_ n: Int) -> Int {

        // inner func

        func makeArray(_ n: Int) -> [Int] {    // String으로 변환 후 각각의 캐릭터 값을 다시 Int형으로 변환

            let convertString = String(n)

            var resultArray: [Int] = []

            for element in convertString {

                if let convertData = Int(String(element)) {

                    resultArray.append(convertData)

                }

            }

            return resultArray

        }

        

        func makeAProduct(_ n: [Int]) -> Int {  // 각각의 데이터를 곱하는 함수

            var result = 1

            for element in n {

                result = result * element

            }

            return result

        }

        

        func makeADigit(_ n: [Int]) -> Int {  // 각각의 데이터를 더하는 함수 

            var result = 0

            for element in n {

                result = result + element

            }

            return result

        }

        // inner func end

        

        // start

        var arrayInt: [Int] = []

        arrayInt = makeArray(n)

        return makeAProduct(arrayInt) - makeADigit(arrayInt)

    }

}

 

마무리

이번 문제에서는 곱셉 함수를 만들다가 한 번 미스를 했다. 0이 들어올 시 건너뛰는 처리를 했었는데 그로 인하여 곱셈 자체가 뒤틀려 버리는 문제가 발생했었다.

언어 : Swift

728x90