전체 글
-
[프로그래머스][Swift] 다트 게임알고리즘 2022. 7. 14. 14:33
func solution(_ dartResult:String) -> Int { let arr = dartResult.map { $0 } var arr2: [Int] = [] var result: Int = 0 for i in 0.. 1 { if arr[i - 2].isNumber == true { result += 10 } } result += Int(String(arr[i - 1]))! } else if arr[i] == "D" { if i > 1 { if arr[i - 2].isNumber == true { result += 10 * 10 } } result += Int(String(arr[i - 1]))! * Int(String(arr[i - 1]))! } else { if i > 1 { if ar..
-
[프로그래머스][Swift] 문자열 내 p와 y의 개수알고리즘 2022. 7. 14. 10:36
func solution(_ s: String) -> Bool { var ans: Bool = false let pNum = s.filter { $0 == "p" || $0 == "P" }.count let yNum = s.filter { $0 == "y" || $0 == "Y" }.count return pNum == yNum ? !ans : ans } 다른 사람의 풀이 func solution2(_ s:String) -> Bool { let string = s.lowercased() return string.components(separatedBy: "p").count == string.components(separatedBy: "y").count } 문자열을 모두 소문자로 바꾼 후 개수 비교 잊고 ..
-
[프로그래머스][Swift] 두 정수 사이의 합알고리즘 2022. 7. 11. 10:16
func solution(_ a:Int, _ b:Int) -> Int64 { return a > b ? Int64((b...a).reduce(0) { $0 + $1 }) : Int64((a...b).reduce(0) { $0 + $1 }) } 다른 사람의 풀이 func solution(_ a:Int, _ b:Int) -> Int64 { return Int64(a + b) * Int64(max(a, b) - min(a, b) + 1) / Int64(2) } 등차수열의 합 공식 사용 등차수열이란 연속하는 두 항의 차이가 모두 일정한 수열 두 항 a, b가 주어졌을 때 n개의 합을 구하는 방식 Sn = (a + b) * n / 2
-
[프로그래머스][Swift] 부족한 금액 계산하기알고리즘 2022. 7. 1. 17:58
import Foundation func solution(_ price:Int, _ money:Int, _ count:Int) -> Int64{ var answer: Int64 = 0 for n in 1...count { answer += Int64(price * n) } if answer - Int64(money) > 0 { return answer - Int64(money) } return 0 } 고차함수 복습하고 다시 풀어봄 import Foundation func solution(_ price:Int, _ money:Int, _ count:Int) -> Int64{ var sum = (1...count).map { $0 * price }.reduce(0) { $0 + $1 } return mone..
-
[프로그래머스][Swift] 자릿수 더하기알고리즘 2022. 6. 26. 22:47
func solution(_ n:Int) -> Int { var answer: Int = n var result: [Int] = [] var value: Int = Int() while answer >= 10 { value = answer % 10 answer = answer / 10 result.append(value) } result.append(answer) return result.reduce(0) { $0 + $1 } } func solution2(_ n:Int) -> Int { var result: Int = Int() for (_, num) in String(n).enumerated() { result += Int(String(num)) ?? 0 } return result } print(s..