DEV Community

Ganesh K S
Ganesh K S

Posted on

Length of consecutive 1's in Binary representation

let input=110
Enter fullscreen mode Exit fullscreen mode
output=3
Enter fullscreen mode Exit fullscreen mode

In order to do this first we need to check whether the binary form of input contains consecutive or not

Image description

n is given input if we do binary and operation between n left shift by 1 the output if it comes non zero then it is having consecutive 1

In order to find the longest consecutive ones in binary representation

Image description

first step - n & n<<1 if it comes non zero then increment the initialized variable count to 1

second step - if non zero number comes up then previous output will become n and again continue step until n equals to zero

function getLongestConsecutiveOnes(n){
  let count=0

  while(n > 0){
    count++;
    n=(n&(n<<1))
  }

   return count;
}

console.log(getLongestConsecutiveOnes(110))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)