Search code examples
javascriptbinarynanbitwise-operatorsbitwise-and

why I am getting 'NaN' for '&' operator?


I am not able to understand why I am getting this "NaN" while performing AND-Bitwise operator for some numbers only? please see pic I attached to understand My issue clearly.

'use strict';

function getMaxLessThanK(n, k) {


  let toknowNum = [];
  let bitVal = [];
  let topop = [];
  if (2 <= n && n <= Math.pow(10, 3) && 2 <= k && k <= n) {
    let z = 0;
    for (let i = 1; i < n; i++) {
      for (let j = 2 + z; j <= n; j++) {
        if (i !== j) {
          toknowNum.push([i, j]);

        }
      }
      z++;
    }

    toknowNum.forEach(val => {
      bitVal.push(parseInt((val[0].toString(2) & val[1].toString(2)), 2))
      console.log( val, parseInt((val[0].toString(2) & val[1].toString(2)), 2))
    })

    bitVal.sort();

    bitVal.forEach(val => {
      if (val < k) {
        topop.push(val);
      }
    })

    return topop.pop();
  }
  console.log(toknowNum, bitVal);
  return 'please check enter values';
}
console.log(getMaxLessThanK(8, 4));

here is my issue pic


Solution

  • This is happening because of bitVal.push(parseInt((val[0].toString(2) & val[1].toString(2)), 2)) line.

    In your example, let's consider val = [4,8] Now, val[0].toString(2) would be 100 and val[1].toString(2) would be 1000.\

    So, when you perform (val[0].toString(2) & val[1].toString(2)) it would be "100" & "1000"(Note that both are strings).

    But, since JS cannot perform bitwise operation on strings, these strings would be converted in to interger (with base 10), so the above operation would be 100 & 1000 (Note that both are converted integers), which will result in a value 96 (Actual value after performing binary &).

    And now, when you try to do bitVal.push(parseInt((val[0].toString(2) & val[1].toString(2)), 2)), it would be bitVal.push(parseInt(96, 2)). Since 96 is not a binary number, the parseInt(96,2) would be NaN.

    To fix this, just update this line to as follow: bitVal.push(val[0] & val[1]).

    Full code as follow:

    'use strict';
    
    function getMaxLessThanK(n, k) {
    
    
      let toknowNum = [];
      let bitVal = [];
      let topop = [];
      if (2 <= n && n <= Math.pow(10, 3) && 2 <= k && k <= n) {
        let z = 0;
        for (let i = 1; i < n; i++) {
          for (let j = 2 + z; j <= n; j++) {
            if (i !== j) {
              toknowNum.push([i, j]);
    
            }
          }
          z++;
        }
    
        toknowNum.forEach(val => {
          bitVal.push(val[0] & val[1])
          console.log(val, (val[0] & val[1]))
        })
    
        bitVal.sort();
    
        bitVal.forEach(val => {
          if (val < k) {
            topop.push(val);
          }
        })
    
        return topop.pop();
      }
      console.log(toknowNum, bitVal);
      return 'please check enter values';
    }
    console.log(getMaxLessThanK(8, 4));