Description
Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0.
Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their bit positions. For example, the two 1's in "1001" have a distance of 3.
Example 1:
Input: n = 22 Output: 2 Explanation: 22 in binary is "10110". The first adjacent pair of 1's is "10110" with a distance of 2. The second adjacent pair of 1's is "10110" with a distance of 1. The answer is the largest of these two distances, which is 2. Note that "10110" is not a valid pair since there is a 1 separating the two 1's underlined.
Example 2:
Input: n = 8 Output: 0 Explanation: 8 in binary is "1000". There are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.
Example 3:
Input: n = 5 Output: 2 Explanation: 5 in binary is "101".
Constraints:
1 <= n <= 109
Solutions
This function finds the maximum binary gap in a number, which is the largest distance between consecutive 1 bits in its binary representation. It first converts the number n to a binary string using toString(2), then iterates through each character to find positions of 1 bits. It tracks the position of the last 1 bit found in the last variable, and whenever a new 1 is encountered, it calculates the distance from the previous 1 using i - last, updating the result res to keep track of the maximum gap found. Finally, it returns the maximum gap.
/**
* @param {number} n
* @return {number}
*/
var binaryGap = function(n) {
const bin = n.toString(2);
let last = -1;
let res = 0;
for (let i = 0; i < bin.length; i++) {
if (bin[i] === '0') {
continue;
}
if (last > -1) {
res = Math.max(res, i - last);
}
last = i;
}
return res;
};