Longest Binary Gap

by rishul matta

JavaScript

function longest(N) {
  if (N ==1 || N == 1 ) {
    return 0;
  }
  let isNegative = false;
  
  if (N < 0) {
    isNegative = true;
    N = Math.abs(N);
  }
  let quo = Infinity;
  let rem, stk;

  stk = [];
  
  while(quo > 0) {
    quo = parseInt(N/2);
    rem = parseInt(N%2);
    stk.push(rem);

    N = quo;
  }

 
    let binary = stk.reverse();
    stk = binary;
  
  if (isNegative) {
  	if (stk.length % 4 != 0) {
    	let n = stk.length % 4;
      while(n>0) {
      	stk.push(0);
        n--;
      }
    }
		
    stk.map((nos, index) => {
    	if (nos == 0) {
      	stk[index] = 1;
      }else {
      	stk[index] = 0;
      }
    });
		// logic to add one to get 2's complement
    
    
  }
  let counter = 0, biggest = 0;

  for (var i = 0; i < binary.length; ++i) {
    if (binary[i] == 0) {
      counter++;
      if (counter > biggest) {
        biggest = counter;
      }
    }
    else {
      counter = 0;
    }
  }

  return biggest;
}