let input=110
output=3
In order to do this first we need to check whether the binary form of input contains consecutive or not
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
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))
Top comments (0)