
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.
1using System;
2
3public class Program {
4 public static int BinaryGap(int n) {
5 int lastPosition = -1, maxGap = 0, idx = 0;
6 while (n > 0) {
7 if ((n & 1) == 1) {
8 if (lastPosition != -1) {
9 maxGap = Math.Max(maxGap, idx - lastPosition);
10 }
11 lastPosition = idx;
12 }
13 n >>= 1;
14 idx++;
15 }
16 return maxGap;
17 }
18 public static void Main() {
19 Console.WriteLine(BinaryGap(22)); // Output: 2
20 }
21}This C# solution iterates bitwise over 'n', tracks positions of '1's, and computes the longest distance between consecutive '1' bits with simple arithmetic.
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.
1def
Convert to a binary string using Python's `bin` function, strip leading '0b', then iterate over the positions of '1's.