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

149
Visualizações
Counting Bits giving not the expected output

Trying to solve the Counting Bits using JavaScript ,basically finding the number of set bits for all numbers from 0 to N and push them in an array and return as answer

Here is explanation

            Input: n = 5
            Output: [0,1,1,2,1,2]
            Explanation:
            0 --> 0
            1 --> 1
            2 --> 10
            3 --> 11
            4 --> 100
            5 --> 101

Here is the solution in Javascript

                const countBits = function (nums){

                   let mem = [];
                   mem[0] = 0;
                   
                   
                   for (let i=0;i<=nums;i++)
                   
                     mem[i] = mem[i/2] + i%2;
                     
                     return mem;


                }

i see output as

            PS C:\VSB-PRO> node Fibo.js
            [ 0, NaN, NaN, NaN, NaN ]

Here is the reference code trying to convert which was previously written in Java

            class Solution {
            public:
                vector<int> countBits(int num) {
                    //mem[i] = No of 1s from 0 to number i
                    vector<int> mem(num+1);
                    mem[0] = 0;
                    
                    for(int i=1;i<=num;++i)
                        mem[i] = mem[i/2] + i%2;
                    
                    return mem;
                }
            };

Your help is very much appreciated

Regards,

Carolyn

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

0

The thing is that in Java / represents integer division when the operands are integers, but in JavaScript, the division will be a floating point division, so that 1/2 == 0.5, and then mem[0.5] will be an undefined value.

Use the bit shift operator instead to get the same behaviour:

const countBits = function(nums) {
  let mem = [0];
  for (let i = 0; i <= nums; i++)
    mem[i] = mem[i >> 1] + i % 2;
  return mem;
}

console.log(countBits(5));

about 4 years ago · Juan Pablo Isaza Relatório

0

Converting positive numbers to a Javascript string object will work for you

console.log(Number(256).toString(2)); // 100000000

If your array contains both positive and negative numbers, then you can use the "unsigned right shift" operator with toString method again.

console.log((-256 >>> 0).toString(2)); // 11111111111111111111111100000000

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