- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Longest distance between 1s in binary JavaScript

We are required to write a JavaScript function that in a positive integer, say n. The function should 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, then we have to 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.

For example −

If the input is 22, then the output should be 2,

because,

- The binary code for 22 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

const num = 22; const binaryGap = (num = 1) => { let last = -1; let ans = 0; // go through every bit for (let i = 0; i < 32; i++) { // check whether the bit is `1`. // if true, calculate the longest distance with // previous `1` if `1` was previously found. if ((num >> i) & 1 > 0) { if (last >= 0) { ans = Math.max(ans, i - last); } last = i; } } return ans; }; console.log(binaryGap(num));

## Output

And the output in the console will be −

2

- Related Questions & Answers
- Program to find longest distance of 1s in binary form of a number using Python
- Finding longest line of 1s in a matrix in JavaScript
- Calculating 1s in binary representation of numbers in JavaScript
- Shortest distance between objects in JavaScript
- Program to find longest consecutive run of 1s in binary form of n in Python
- Distance of nearest 0 in binary matrix in JavaScript
- Hamming Distance between two strings in JavaScript
- Sorting according to number of 1s in binary representation using JavaScript
- Find distance between two nodes of a Binary Tree in C++
- JavaScript - find distance between items on array
- Find distance between two nodes of a Binary Tree in C++ Program
- Program to find length of longest substring with 1s in a binary string after one 0-flip in Python
- Distance between 2 duplicate numbers in an array JavaScript
- Check if a binary string has a 0 between 1s or not in C++
- Levenshtein Distance in JavaScript

Advertisements