티스토리 뷰

문제.BinaryGap

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:

function solution($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.

풀이

  • 과정
    1. 이진수 변환
    2. 이진 간격 찾기
  • 관련 함수
    • array_push()
    • explode()
    • implode()
    • array_reverse()

 

# php

function solution($N) {
    // write your code in PHP7.0

    // get binary vaolue
    $n = 2;
    if($N>0){
        $num = $N;
        $binary = Array();
        
        //	이진수 변환
        while(true){            
            $q = (int)($num/$n);
            $r = (int)($num%$n);
            array_push($binary, $r);            

            if( $q>0 ){
                $num = $q;
            }else{
                break;
            }
        }
		
        // 간격 구하기
        $count = 0;
        $max_count = 0;
        $set_binary = array_reverse($binary);
        foreach($set_binary as $k=>$v){
            if($v == 1){
                if($count>$max_count){
                    $max_count = $count;
                }
                $count = 0;
            }else{
                $count++;
            }
        }
        
        return $max_count;
    }else{
        return false;
    }    
}

 

# python

# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")

def solution(N):
    # write your code in Python 3.6
    num = N
    binarys = []

    # 2진수 변환
    while True:
        a = int(num/2)
        b = num%2
        binarys.append(b)

        if a>0:            
            num = a
        else:
            break

    # 1과 1사이 간격
    count = 0
    max = 0
    binarys.reverse()
    for i in range(len(binarys)):
        if binarys[i] == 1:
            if count > max:
                max=count
            count = 0
        else:
            count+=1
            
    return max

 

# python - 다른사람 풀이

파이썬 문법을 활용하여 정말 심플하게 작성하였다.

  • bin() : 진법 변환, 반환타입 string  / [2:]  반환값에 진법 미표기 
  • strip(A) : 문자열 시작 끝에 있는 문자 'A' 의 연속 문자 모두 제거
  • split(A) : 문자열 중, 문자 'A'를 기준으로 자른다.
def solution(N):
    # write your code in Python 3.6
    binary = bin(N)[2:]
    return len(max(binary.strip('0').strip('1').split('1')))

 

* 출처
Codility_ [바로가기]

댓글