Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading