
Sponsored
Sponsored
This approach involves converting the number into its binary representation and then finding the positions of '1's. We will iterate through the binary string, keep track of the last position where a '1' was found, and calculate the distance from the current '1' to the last. Record the maximum distance found.
Time Complexity: O(log n) — The number of iterations is proportional to the number of bits, which is log2(n).
Space Complexity: O(1) — Only a few variables are used.
1#include <iostream>
2#include <algorithm>
3using namespace std;
4
5int binaryGap(int n) {
6 int lastPosition = -1, maxGap = 0, idx = 0;
7 while (n > 0) {
8 if (n & 1) {
9 if (lastPosition != -1) {
10 maxGap = max(maxGap, idx - lastPosition);
11 }
12 lastPosition = idx;
13 }
14 n >>= 1;
15 idx++;
16 }
17 return maxGap;
18}
19
20int main() {
21 cout << binaryGap(22) << endl; // Output: 2
22 return 0;
23}The method efficiently iterates over the bits of 'n', updating the index 'idx' and checking for '1'. Updates are made to 'maxGap' using the difference between current and last seen '1' positions.
This approach involves converting the integer to its binary string representation, iterating through the string to find indices of '1's, and calculating and storing the distances between consecutive '1's to find the maximum gap.
Time Complexity: O(log n)
Space Complexity: O(log n) due to storage of binary string.
1function
JavaScript's `toString(2)` method converts the integer to binary. The method then iterates over the string to find and evaluate gaps between '1's.