-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryGaps.cpp
47 lines (38 loc) · 978 Bytes
/
BinaryGaps.cpp
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
// Code was writen for Codility
#include <iostream>
std::string binaryDecomposition(int N);
int countSequences(std::string number);
int solution(int N)
{
std::string number;
number = binaryDecomposition(N);
return countSequences(number);
}
std::string binaryDecomposition(int N)
{
std::string number, temp;
int moduloNumber;
while (N != 0)
{
moduloNumber = N % 2;
N = N / 2;
number += moduloNumber == 1 ? "1" : "0";
}
for (int i = number.size() - 1; i >= 0; i--)
temp += number[i];
return temp;
}
int countSequences(std::string number)
{
int lengthOfSequence = 0, newLength;
for (unsigned long i = 0; i < number.size(); i++)
{
if ('1' == number[i])
{
lengthOfSequence = newLength > lengthOfSequence ? newLength : lengthOfSequence;
newLength = 0;
} else if ('0' == number[i])
newLength++;
}
return lengthOfSequence;
}