Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

180
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda