Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
Bitwise - Why 0 & 1 !== 1 & 1 return false in VSCode/Leetcode?

I was writing an algorithm to compare how many bits are different between 2 numbers using this function

 var hammingDistance = function(x, y) {
  let result = 0;
  while (x !== 0 || y !== 0) {
    // This line is incorrect
    if (x & 1 !== y & 1) result++;
    x = x >> 1;
    y = y >> 1;
  }
  return result;
};

But my result is always 1 less than the correct answer, and it turns our my function is wrong when comparing the left most digit, such as 0011 and 0100. It returns 2 instead of 3.

https://i.imgur.com/P46RyZr.png

I can use XOR instead of !== to get the correct answer. But I'm wondering why?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Your problem is that !== has a higher precedence than &. So your condition is actually (x & (1 !== y)) & 1. Use explicit grouping instead:

if ((x & 1) !== (y & 1)) result++;

It works with ^ because that has a lower precedence than &.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!