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
'알고리즘 > 해결' 카테고리의 다른 글
LeetCode977. Squares of a Sorted Array (0) | 2020.01.26 |
---|---|
LeetCode709. To Lower Case (0) | 2020.01.26 |
LeetCode 905. Sort Array By Parity (0) | 2020.01.19 |
LeetCode 1207. Unique Number of Occurrences (0) | 2020.01.19 |
LeetCode 1108. Defanging an IP Address (0) | 2020.01.12 |