Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

197
Visualizações
Java script convert number to string base two

I am doing a test and the task is to write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.

So i have the following problem : while my code runs ok for the most part and passes all tests when the inputs are 9843520790 and 8989787640 I am getting wrong results. So I hoped in the calc and made this numbers binary and tried couple of console.log(bNum) and what I noticed is that I loose the high byte during the conversion. Meaning that after bNum=(n>>>0).toString(2); the console.log(bNum) returns 11001001100011110010110101110011 for 7676570995 when it should return 111001001100011110010110101110011.

 var countBits = function(n) {
  let bNum=(n>>>0).toString(2);//converts int to base 2 
  console.log(bNum);
  let sum=0;
  for(let i=0;i<=bNum.length-1;i++)
    {
       if(bNum[i]==1)
         sum+=1;
    }
  return sum;
};

I am not asking for a coding solution just someone to explain why this is happening so I can find a wayto fix it.Thanks in advance :)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think your issue is n>>>0. I not to familiar with the >>>0 but as far as I know it converts the input to a 32bit unsigned in. The max value for an uint is 4294967295 so those numbers exceed it. Therefore I think some information is lost in the conversion.

 var countBitsOld = function(n) {
  let bNum=(n>>>0).toString(2);//converts int to base 2 
  let sum=0;
  for(let i=0;i<=bNum.length-1;i++)
    {
       if(bNum[i]==1)
         sum+=1;
    }
  return sum;
};
 var countBitsNew = function(n) {
  let bNum=(n).toString(2);//converts int to base 2 
  let sum=0;
  for(let i=0;i<=bNum.length-1;i++)
    {
       if(bNum[i]==1)
         sum+=1;
    }
  return sum;
};

const test = (n) => console.log({old: countBitsOld(n), new: countBitsNew(n)});
test(9843520790);
test(8989787640);
test(76765709950);

.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda