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

119
Visualizações
Number of 1 Bits with Javascript

Question: Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).

Example 1:

Input: n = 00000000000000000000000000001011

Output: 3

Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

My Code

var hammingWeight = function(n) {
    for (i=0; i<32; i++) {
        var mask = 1;
        var count = 0;
        if ((mask & n) != 0 ) {            
            mask <<= 1;
            count++;
        }    
        return count;
    }
};

Test Case:

00000000000000000000000000001011
00000000000000000000000010000000
11111111111111111111111111111101

Expected Output:

3
1
31

Output:

1
0
1

What did I do wrong with my code?

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

0

You have a few issues here:

  • You are redefining count and mask inside of your for loop.
  • You are returning after the first iteration of the loop, instead of waiting for the whole thing to count up.
  • You only shift mask if a bit is 1.

Here is a corrected function:

var hammingWeight = function(n) {
    var count = 0;
    var mask = 1;
    for (i=0; i<32; i++) {
        if ((mask & n) != 0 ) {            
            count++;
        }
        mask <<= 1;
    }
    return count;
};
about 4 years ago · Juan Pablo Isaza Relatório

0

A shorter way to write this could be:

const hammingWeight = value => [...value].filter(f => f == 1).length;

Explanation:

[...value] this will create an array of 0's and 1's based on your string

.filter(f => f == 1) will filter the array, keeping only the 1 values

.length gives you the length of the filtered array

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