
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.
1public class BinaryGap {
2 public static int binaryGap(int n) {
3 int lastPosition = -1, maxGap = 0, idx = 0;
4 while (n > 0) {
5 if ((n & 1) == 1) {
6 if (lastPosition != -1) {
7 maxGap = Math.max(maxGap, idx - lastPosition);
8 }
9 lastPosition = idx;
10 }
11 n >>= 1;
12 idx++;
13 }
14 return maxGap;
15 }
16 public static void main(String[] args) {
17 System.out.println(binaryGap(22)); // Output: 2
18 }
19}This solution involves bit manipulation to determine '1's in the binary format and compute the maximum gap between successive '1's.
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.
1publicUtilize Java's `toBinaryString` to convert the integer and iterate to find the indices of '1's. Calculate distances and select the maximum.