SW/알고리즘

Codility : BinaryGap : C++ : 문제 풀이

얇은생각 2019. 10. 30. 07:30
반응형

풀이

// you can use includes, for example:
// #include <algorithm>
#include <cmath>
using namespace std;

// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int checkBinGap(int bn[], int size, int pos){
    int retVal = 0;

    if(bn[pos] == 1){
        for(int i = pos+1; i < size; i++){
            if(bn[i] == 0){
                ++retVal;
            }else{
                return retVal;
            }
        }
    }
    else{
        return 0;
    }
    return 0;
}


int getBinGap(int bn[], int size){
    int maxVal = 0;

    for(int i=0; i < size; i++){
        maxVal = max(maxVal, checkBinGap(bn, size, i));
    }
    return maxVal;
}

int solution(int N) {
    // write your code in C++14 (g++ 6.2.0)
    // array to store binary number 
    int binaryNum[32]; 
  
    int i = 0; 
    while (N > 0) { 
        binaryNum[i] = N % 2; 
        N = N / 2; 
        i++; 
    }
    
    
    return getBinGap(binaryNum, i+1);
}

 

 

 

실행 결과

ASKS DETAILS : EASY

BinaryGap : Find longest sequence of zeros in binary representation of an integer.

Task Score : 100%

Correctness : 100%

Performance : Not assessed

 

 

 

총평

우선,  binary로 수를 변환해서, 배열에 담아주었습니다. 그 다음, 해당 위치에서 binary gap의 값을 가져오고, 최대값을 보유하도록 함수를 구현하였습니다. 따라서 총 2개의 함수를 구현하였고, 현재 위치에서 binary gap을 구현하도록 하고, 그 값들을 최대값으로 반환하도록 하였습니다. 다양한 방식이 존재하지만, 처음으로 코딜리티 문제를 풀어보면서 프로그래머스랑은 다른 재미를 가지게 해주는 것 같습니다. 앞으로 프로그래머스, 코딜리티 사이트까지, 꾸준히 문제를 풀어나가야 할 것 같습니다.

반응형