
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 <stdio.h>
2#include <math.h>
3
4int binaryGap(int n) {
5 int lastPosition = -1, maxGap = 0, idx = 0;
6 while (n > 0) {
7 if (n & 1) { // If the current bit is 1
8 if (lastPosition != -1) {
9 maxGap = fmax(maxGap, idx - lastPosition);
10 }
11 lastPosition = idx;
12 }
13 n >>= 1;
14 idx++;
15 }
16 return maxGap;
17}
18
19int main() {
20 printf("%d\n", binaryGap(22)); // Output: 2
21 return 0;
22}We use bitwise operations to track positions of '1's in the binary form of 'n'. Each time a '1' is encountered, compare the current index with the last position of '1' to update the maximum gap. Shift bit to the right after each check until 'n' is 0.
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.