Algorithm
Problem Name: 461. Hamming Distance
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x
and y
, return the Hamming distance between them.
Example 1:
Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different.
Example 2:
Input: x = 3, y = 1 Output: 1
Constraints:
0 <= x, y <= 231 - 1
Code Examples
#1 Code Example with C Programming
Code -
C Programming
int hammingDistance(int x, int y) {
int k = x ^ y;
int n = 0;
while (k) {
n ++;
k = k & (k - 1); // reduce one bit
}
return n;
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with C++ Programming
Code -
C++ Programming
class Solution {
public:
int hammingDistance(int x, int y) {
int n = x^y;
int d = 0;
while(n) n &= n-1, d++;
return d;
}
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Java Programming
Code -
Java Programming
class Solution {
public int hammingDistance(int x, int y) {
int xor = x ^ y;
int count = 0;
while (xor != 0) {
if (xor % 2 == 1) {
count++;
}
xor = xor >> 1;
}
return count;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with Javascript Programming
Code -
Javascript Programming
const hammingDistance = function (x, y) {
let d = 0
let h = x ^ y
while (h > 0) {
d++
h &= h - 1
}
return d
}
Copy The Code &
Try With Live Editor
Input
Output
#5 Code Example with Python Programming
Code -
Python Programming
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
return sum(a != b for a, b in zip(bin(x)[2:].zfill(32), bin(y)[2:].zfill(32)))
Copy The Code &
Try With Live Editor
Input
Output
#6 Code Example with C# Programming
Code -
C# Programming
namespace LeetCode
{
public class _0461_HammingDistance
{
public int HammingDistance(int x, int y)
{
var xor = x ^ y;
var count = 0;
while (xor > 0)
{
if ((xor & 1) == 1) count++;
xor >>= 1;
}
return count;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output