Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Longest distance between 1s in binary JavaScript
We are required to write a JavaScript function that takes a positive integer n and finds the longest distance between any two adjacent 1's in its binary representation.
If there are no two adjacent 1's, the function returns 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.
Understanding the Problem
For example, in the binary representation "1001", the two 1's have a distance of 3 (positions 0 and 3).
Let's examine the number 22:
- Binary representation of 22 is 10110
- First adjacent pair: positions 1 and 2 (distance = 1)
- Second adjacent pair: positions 2 and 4 (distance = 2)
- The maximum distance is 2
Algorithm
We iterate through each bit of the number, track the position of the last found 1, and calculate distances between consecutive 1's:
const num = 22;
const binaryGap = (num = 1) => {
let last = -1;
let ans = 0;
// Go through every bit (32-bit integer)
for (let i = 0; i < 32; i++) {
// Check if the current bit is 1
if ((num >> i) & 1 > 0) {
// If we found a previous 1, calculate distance
if (last >= 0) {
ans = Math.max(ans, i - last);
}
last = i; // Update last position of 1
}
}
return ans;
};
console.log(`Binary of ${num}: ${num.toString(2)}`);
console.log(`Longest distance: ${binaryGap(num)}`);
Binary of 22: 10110 Longest distance: 2
Step-by-Step Example
Let's trace through the algorithm with num = 22 (binary: 10110):
const traceExample = (num) => {
let last = -1;
let ans = 0;
console.log(`Number: ${num}, Binary: ${num.toString(2)}`);
console.log("Bit position | Bit value | Action");
console.log("-------------|-----------|-------");
for (let i = 0; i < 8; i++) { // Using 8 bits for clarity
let bit = (num >> i) & 1;
let action = "";
if (bit === 1) {
if (last >= 0) {
let distance = i - last;
ans = Math.max(ans, distance);
action = `Distance from pos ${last}: ${distance}`;
} else {
action = "First 1 found";
}
last = i;
} else {
action = "Skip (bit is 0)";
}
console.log(` ${i} | ${bit} | ${action}`);
}
return ans;
};
traceExample(22);
Number: 22, Binary: 10110
Bit position | Bit value | Action
-------------|-----------|-------
0 | 0 | Skip (bit is 0)
1 | 1 | First 1 found
2 | 1 | Distance from pos 1: 1
3 | 0 | Skip (bit is 0)
4 | 1 | Distance from pos 2: 2
5 | 0 | Skip (bit is 0)
6 | 0 | Skip (bit is 0)
7 | 0 | Skip (bit is 0)
Testing with Different Numbers
const binaryGap = (num = 1) => {
let last = -1;
let ans = 0;
for (let i = 0; i < 32; i++) {
if ((num >> i) & 1 > 0) {
if (last >= 0) {
ans = Math.max(ans, i - last);
}
last = i;
}
}
return ans;
};
// Test cases
const testCases = [5, 6, 8, 22, 1041];
testCases.forEach(num => {
console.log(`Number: ${num}, Binary: ${num.toString(2)}, Gap: ${binaryGap(num)}`);
});
Number: 5, Binary: 101, Gap: 2 Number: 6, Binary: 110, Gap: 1 Number: 8, Binary: 1000, Gap: 0 Number: 22, Binary: 10110, Gap: 2 Number: 1041, Binary: 10000010001, Gap: 5
Key Points
- We use bit shifting (
>>) and bitwise AND (&) to check individual bits - The algorithm has O(log n) time complexity since we check at most 32 bits
- Space complexity is O(1) as we only use a few variables
- Returns 0 if there are fewer than two 1's in the binary representation
Conclusion
This solution efficiently finds the longest gap between adjacent 1's by iterating through bit positions and tracking distances. The bit manipulation approach provides optimal performance for this binary analysis problem.
