Given a time in -hour AM/PM format, convert it to military (24-hour) time.
func timeConversion(s: String) -> String {
//split / components / subscript / index
var ans = s.map { $0 } // or copy-inout
if s.contains("P") {
ans.replaceSubrange(0...1, with: String(Int(s.split(separator: ":")[0])!+12))
if ans[0] == "2" && ans[1] == "4" {
ans.replaceSubrange(0...1, with: "12")
}
} else {
if ans.starts(with: ["1","2"]) {
ans.replaceSubrange(0...1, with: "00")
}
}
ans.removeSubrange(s.count-2..<s.count)
return String(ans)
}
The code looks a little messy and inefficient. so I attached another method from
https://github.com/aleksandar-dinic/HackerRank-Solutions/
func timeConversion(_ str: String) -> String {
guard let hour = Int(str.prefix(2)) else { fatalError("Bad input") }
var time = String(str.dropLast(2))
if str.hasSuffix("PM"), hour < 12 {
time = String(time.dropFirst(2))
time = "\(hour+12)\(time)"
} else if str.hasSuffix("AM"), hour == 12 {
time = String(time.dropFirst(2))
time = "00\(time)"
}
return time
}
}
It looks much better. why did I change the String to Array?
I won't remember the grammar or something I used before.
[References]
https://developer.apple.com/documentation/swift/sequence/starts(with:)
'Computer Science > Algorithm with Code' 카테고리의 다른 글
Hacker Rank_5/54 tests (Easy, Lonely Integer) (0) | 2024.05.09 |
---|---|
Hacker Rank_4/54 tests (Easy, Sparse Array) (0) | 2024.05.09 |
Hacker Rank_2/54 tests (Easy, Min-Max Sum) (0) | 2024.05.07 |
Hacker Rank_1/54 tests (Easy, Plus Minus) (0) | 2024.05.07 |
Updated_Hacker Rank (Intermediate, Equal) (0) | 2024.05.06 |