Given a positive integer n
, find and return the longest distance between any two consecutive 1’s in the binary representation of n
. If there are no two consecutive 1’s, return 0.
Before diving into the solution, let’s clarify a few points:
n
?
1 <= n <= 10^9
Here’s a step-by-step approach to solve this problem:
n
into its binary form.Below is the Java code that implements the above strategy:
public class Solution {
public int binaryGap(int n) {
String binaryString = Integer.toBinaryString(n);
int lastPos = -1;
int maxDistance = 0;
for (int i = 0; i < binaryString.length(); i++) {
if (binaryString.charAt(i) == '1') {
if (lastPos != -1) {
maxDistance = Math.max(maxDistance, i - lastPos);
}
lastPos = i;
}
}
return maxDistance;
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.binaryGap(22)); // Output: 2
System.out.println(solution.binaryGap(5)); // Output: 2
System.out.println(solution.binaryGap(6)); // Output: 1
System.out.println(solution.binaryGap(8)); // Output: 0
}
}
n
to a binary string takes (O(\log n)) time.n
.Integer.toBinaryString(n)
method converts the integer n
to its binary representation.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?