알고리즘 & 코딩테스트/프로프래머스
[프로그래머스 코테 기초 Swift] #4-4 조건 문자열
U_Daeng
2024. 5. 23. 18:58
프로그래머스 코딩 기초 트레이닝의 Day4은 "연산, 조건문"에 관한 문제다
🗒️ 문제


✏️ 내 풀이
import Foundation
func solution(_ ineq:String, _ eq:String, _ n:Int, _ m:Int) -> Int {
var result: Int = 0
if(ineq == "<" && eq == "="){
if(n <= m) {
result = 1
}
}
else if(ineq == "<" && eq == "!") {
if(n < m) {
result = 1
}
}
else if(ineq == ">" && eq == "="){
if(n >= m) {
result = 1
}
}
else if(ineq == ">" && eq == "!") {
if(n > m) {
result = 1
}
}
return result
}
ineq와 eq로 나올 수 있는 조합을 조건문으로 구분하여
조건문에 해당할 때 result값을 1로 바꾸고 아닌 경우는 걸러져서 0을 반환하게끔 했다
근데 왠지 느낌상으로는 이 모든 조건문을 어쨌든 다 타야하기 때문에 조금 비효율적인가?싶긴했슴
🔍 다른 풀이
1)
func solution(_ ineq:String, _ eq:String, _ n:Int, _ m:Int) -> Int {
switch ineq+eq {
case ">=": return n >= m ? 1 : 0
case "<=": return n <= m ? 1 : 0
case ">!": return n > m ? 1 : 0
case "<!": return n < m ? 1 : 0
default: return 0
}
}
2)
func solution(_ ineq:String, _ eq:String, _ n:Int, _ m:Int) -> Int {
let result: Bool
switch (ineq, eq) {
case (">", "="): result = n >= m
case ("<", "="): result = n <= m
case (">", "!"): result = n > m
case ("<", "!"): result = n < m
default: result = false
}
return result ? 1 : 0
}
다른 분들 풀이를 보니 switch문을 활용하셨더라..
연산자들이 문자열이기 때문에 그냥 + 로 붙여버려서 써도되고 튜플로도 사용이 가능하다
세상엔 똑똑한 사람들이 참 많다.. 신기하군