-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongBinaryGapZero.cpp
More file actions
71 lines (58 loc) · 1.66 KB
/
LongBinaryGapZero.cpp
File metadata and controls
71 lines (58 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
using namespace std;
#include <bitset>
int solution(int N) {
// write your code in C++14 (g++ 6.2.0)
char testForZero = '0';
char testForOne ='1';
const int bitSetRange = 64;
int zeroBinGapCounter =0, count0=0;
bool setStartGap = 0;
std::string binary = std::bitset<bitSetRange>(N).to_string();
//cout<<"The binary size:"<<binary.size();
//cout<<"The binary number:"<<binary;
for(int cnt =0;cnt<binary.size();cnt++)
{
if(binary[cnt] == testForOne && setStartGap == 0)//start of Gap
{
setStartGap = 1;//true;
count0 = 0;
//cout<<"\n"<<"setStartGap value in condition 1"<<"\t"<<setStartGap;
}
// cout<<"\n"<<"cnt"<<cnt;
//cout<<"\n"<<"binary digit"<<binary[cnt];
if(binary[cnt] == testForZero && setStartGap == 1)
{
count0++;
//cout<<"count0:"<<"\t"<<count0;
}
else if(binary[cnt] == '1' && setStartGap == 1)//end of Gap
{
if(zeroBinGapCounter < count0)
{
zeroBinGapCounter = count0;
count0 =0;
}
}
}
//Results
if(zeroBinGapCounter ==0)
{
return 0;
}
else
{
//cout<<"zeroBinGapCounter:"<<zeroBinGapCounter;
return zeroBinGapCounter;
}
}
int main()
{
int binaryGapNum =0;
int Number =0;
cout<<"Enter the Number: ";
cin>>Number;
binaryGapNum = solution(Number);
cout<<"The longest binary gap is :"<<binaryGapNum;
return 0;
}