[코딜리티] 레슨 1 - Binary Gap (Swift)

devapploper·2024년 8월 10일
public func solution(_ N : Int) -> Int {
    var num = N, string = ""

    while num > 0 {
        let remainder = num % 2
        string += String(remainder)
        num /= 2
    }

    var maxCount = 0, count = 0
    for i in stride(from: string.count-1, through: 0, by: -1) {
        let index = string.index(string.startIndex, offsetBy: i)
        if string[index] == "1" {
            maxCount = max(maxCount, count)
            count = 0
        } else {
            count += 1
        }
    }

    return maxCount
}
profile
iOS, 알고리즘, 컴퓨터공학에 관련 포스트를 정리해봅니다

0개의 댓글