Algorithm

진수변환과 문자열 인덱스를 통한 알고리즘

GREEN.1229 2021. 6. 22. 14:15

아래 문제는 코딜리티에서 제공하는 Binary Gap의 문제입니다🧑🏻‍💻

문제 제시

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.

Write a function:

class Solution { public int solution(int N); }

that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.

For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.

Write an efficient algorithm for the following assumptions:

  • N is an integer within the range [1..2,147,483,647].Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

문제 해결

import Foundation
import Glibc

public func solution(_ N : Int) -> Int {
    let binaryStr = String(N, radix: 2)
    var cnt: Int = 0
    var maxCnt: Int = 0
    
    for i in 0..<binaryStr.count {
        let index = binaryStr.index(binaryStr.startIndex, offsetBy: i)
        if(binaryStr[index] == "1") {
            if(cnt > maxCnt) {
                maxCnt = cnt
            }
            cnt = 0
        } else {
            cnt += 1
        }
    }
    return maxCnt
}

사용된 개념

 - 10진 -> 2진 변환

 - 문자 인덱스

 - 반복 / 조건문

문제 뒷담화

이번 문제는 우선 10진을 2진으로 변환하는것이 첫번째였다.

그리고 해당 2진 문자열을 가지고 1과 1사이에 0의 갯수를 파악하고 그 최대로 사이에 껴서 연속된 0의 카운트를 구하는것이였다.

우선 반복문을 문자열의 수만큼 돈다.

문자열의 첫인덱스부터 offsetBy: i 를 적용하여 돌며 1이면 맥스카운터와 비교하고 초기화를 해준다.

그리고 0이라면 카운터를 1씩 증가시켜 0의 연속 갯수를 저장해준다.

그리고 마지막으로 맥스카운터를 반환해주면 되는 문제였다.

이게 코딜리티의 레슨 1이여서 쉬운가보다 했는데, 생각보다 까다롭게 생각하면 쌩판 기초는 아닌것 같았다.

그렇지만 정답만 맞추는 되는 문제여서 효율성보다는 정확성에 초점을 두고 풀었는데..!

코딜리티를 하고(얼마 되진 않았지만..!?) 처음으로 100%의 쾌거를 달성했다🙌

이맛에 코딜리티 푸나봄..

이렇게 다양한 조건들이 있었다...!