LoginSignup
1
1

More than 5 years have passed since last update.

【codility】Lesson 1: Iterations BinaryGap

Last updated at Posted at 2018-06-01

subject

Lesson 1: Iterations BinaryGap
整数を2進数に置き換える。その際に、1で囲まれた部分をBinaryGapとし、その長さlengthを求める。
1つの整数でも、複数のBinaryGapがある場合が存在する。その場合は、1番長いBinaryGapを返すプログラムを作成する。
例)N=1041の場合
(1041)10 = (10000010001)2
この場合は、length=3, length = 5のBinaryGapが2つあることになり、return 5が正解である。

submit

「submitするとコードは書き換えられなくなる。よろしいでしょうか?」と聞かれるので少しドキドキしたが、無事にパーフェクトがとれた。
L1_00_binaryGap.png

program

point:コンテナクラスのsetを使ったところ
理由は、最長のBinaryGapの長さを返却値とするためである。
1つの整数に複数のBinaryGapがあり、自動的にソートされるsetが最適だと思った。setのソートは値が小さい順になっているようなので、returnの部分にrebeginを使ってみた。
※ただし、setは重複した値を持つことができないので、1つの整数に同じ長さのBinaryGapがあった場合、配列の数=BinaryGapの数ではなくなる。(今回は聞かれてないのでこれでOK)

binaryGap.cpp
#include<iostream>
#include<sstream>
#include<set>
using namespace std;

int solution(int N) {

    unsigned int        value = N;
    const unsigned int  comp = 1;
    set<int>            binaryGapLength;
    bool                countGapFlag = false;
    int                 countGap = 0;

    while (value > 0) {
        if ((value & comp) == 1)
        {
            if (countGap != 0) {
                binaryGapLength.insert(countGap);
                countGap = 0; //reset countGap
            }
            countGapFlag = true;
        }
        else {
            if (countGapFlag == true)
                countGap++;
        }
        value = value >> 1;
    }
    if( binaryGapLength.empty())
        return 0;
    else
        return *binaryGapLength.rbegin();
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1