본문 바로가기

Computer Science/Algorithm with Code

Hacker Rank_3/54 tests (Easy, Time Conversion)

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:)

 

starts(with:) | Apple Developer Documentation

Returns a Boolean value indicating whether the initial elements of the sequence are the same as the elements in another sequence.

developer.apple.com

https://babbab2.tistory.com/92