#include using namespace std; /* 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: class Solution { public int solution(int 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. */ int solution(int N) { bitset<32> bs(N); if (bs.none() || bs.all()) return 0; int maxGap = 0; int numZeros = 0; bool oneSeen = false; // a bit val of '1' has been seen before // this bit // test oneSeen action // --- ------- ---- // 0 0 continue // 0 1 numZeros++ // 1 0 numZeros = 0, oneSeen = true // 1 1 maxGap = max(maxGap, numZeros); numZeros = 0 for (size_t i = 0; i < bs.size(); i++) { // truth table // ----------- // bit oneSeen action // --- ------- ------ // 0 0 continue // 0 1 numZeros++ // 1 0 numZeros = 0, onSeen = true // 1 1 calc maxGap, numZeros = 0 if (bs.test(i) == 0 && oneSeen == false) continue; else if (bs.test(i) == 0 && oneSeen == true) numZeros++; else if (bs.test(i) == 1 && oneSeen == false) { numZeros = 0; oneSeen = true; } else if (bs.test(i) == 1 && oneSeen == true) { maxGap = max(maxGap, numZeros); numZeros = 0; } } return maxGap; } int main(void) { vector> testCases = { // n maxGap { 9, 2 }, // 1001 {529, 4 }, // 1000010001 { 20, 1 }, // 10100 { 15, 0 }, // 1111 { 32, 0 }, // 100000 }; for (auto tc: testCases) { int input = get<0>(tc); int expected = get<1>(tc); int result = solution(input); int width = 10; cout << setw(width) << "input: " << input << endl; cout << setw(width) << "result: " << result << endl; cout << setw(width) << "expected: " << expected << endl; cout << "-----------------\n"; } }