
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.
1function binaryGap(n) {
2 let lastPosition = -1, maxGap = 0, idx = 0;
3 while (n > 0) {
4 if (n & 1) {
5 if (lastPosition !== -1) {
6 maxGap = Math.max(maxGap, idx - lastPosition);
7 }
8 lastPosition = idx;
9 }
10 n >>= 1;
11 idx++;
12 }
13 return maxGap;
14}
15
16console.log(binaryGap(22)); // Output: 2We employ bit manipulation in JavaScript to find '1's and compute gaps using binary operations, updating the maximum distance found.
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.