Search code examples
javascriptbitwise-operators

What is wrong with my solution?(hackerrank exercise - bitwise operation)


the link for the excersize In short, ‘n’ is series of number from 1 to n, and ‘k’ is a number. I need to return the largest result of a&b (a<b) as long as it’s smaller than k, for example 1&2, 1&3 …2&3,2&4…

I get 0 whenever I run this function:

function getMaxLessThanK(n, k) {
  let maxPV = 0;
  for (let a = 1; a < n; a++) {
    for (let b = a + 1; b <= n; b++) {
      if (a & b < k && a & b > maxPV) {
        maxPV = (a & b)
      }
    }
  }
  return maxPV
}

Solution

  • It's an operator precedence problem.

    Comparison operators (<, >, ...) have higher precedence than bitwise AND (&), so you need to use parentheses to group:

    if ((a & b) < k && (a & b) > maxPV) {
        // ...
    }
    

    Complete snippet:

    function getMaxLessThanK(n, k) {
      let maxPV = 0;
      for (let a = 1; a < n; a++) {
        for (let b = a + 1; b <= n; b++) {
          if ((a & b) < k && (a & b) > maxPV) {
            maxPV = (a & b);
          }
        }
      }
      return maxPV;
    }
    
    console.log(getMaxLessThanK(8, 5));