Home > Software design >  Counting Bits giving not the expected output
Counting Bits giving not the expected output

Time:01-04

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

CodePudding user response:

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));

CodePudding user response:

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

  •  Tags:  
  • Related