ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [codility] Iterations - BinaryGap 문제풀이
    Algorithm 2021. 9. 6. 12:56

     

    문제 원본

     

    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:

    public func solution(_ N : Int) -> Int

    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].

     

    문제 해설

    1 .. 2,147,483,647 사이의 정수의 N값이 주어짐

    0이 연속된 숫자중 가장 큰 수를 구하기

     

     

    구현 해설

    1. 입력받은 정수를 2진수 문자열로 변환

    2. 문자열 1인경우 현재0의 갯수를 저장, 단 저장된 값보다 현재 0이 갯수가 큰경우에만 저장

    시간복잡도 : O(N)

    import Foundation
    import Glibc
    
    // you can write to stdout for debugging purposes, e.g.
    // print("this is a debug message")
    
    public func solution(_ N : Int) -> Int {
        // write your code in Swift 4.2.1 (Linux)
    
        let binary = String(N, radix: 2)
        
        var saveCount = 0
        var cursorCount = 0
        
        for character in binary {
            if character == "1" {
                if saveCount < cursorCount {
                    saveCount = cursorCount
                }
                cursorCount = 0
            } else {
                cursorCount += 1
            }
        }
        
        return saveCount
    }

     

     

    댓글

Designed by Tistory.