---
# System prepended metadata

title: Hamming Distance

---

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, calculate the Hamming distance.


Note:
$0 ≤ x,y < 2^{31}$ .

```
Example:

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.
```

```c=
/*
 * Provided by Lin,Bo-Yu.
 */
 
#include <stdio.h>
#include <stdlib.h>

int hammingDistance(int x, int y){
    int data = x^y; // XOR
    int result = 0;
    
    for(int i =0; i< sizeof(int)*8; i++){
        result += ((data>>i) & 1);
    }
    return result;
}

int main()
{
    int input1 = 51;
    int input2 = 23;
    
    printf("Result = %d",hammingDistance(input1, input2));
    return 0;
}
```


```c=
/*
 * Provided by Nian,Bohong.
 */
 
#include <stdio.h>
#include <stdlib.h>


/**
 * Provide hamming distance for variable x and y
 */
int hammingDistance(int x, int y)
{
    /* Get operate of exclusive or from variable x and y */
    int x_y_xor = x ^ y;
    
    /* Stored result by variable result */
    int result = 0;
    
    for(int binary_idx = 0; binary_idx < sizeof(int)*8; binary_idx++) {
    
        /* If result of operating is equal one, resule increase */
        if((x_y_xor >> binary_idx) & 0x01 == 1) {
            result = result + 1;
        }
    }
    
    return result;
}

int main()
{
    int input1 = 51;
    int input2 = 23;
    
    printf("Result = %d",hammingDistance(input1, input2));
    return 0;
}
```

```c=
/*
 * Provided by C.M. Lai
 */
 
#include <stdio.h>
#include <stdlib.h>
/**
 * Provide hamming distance for variable x and y
 */
int hammingDistance(int x, int y)
{
    /* Get operate of exclusive or from variable x and y */
    int x_y_xor = x ^ y;
    
    /* Stored result by variable result */
    int result = 0;
    int bitcheck = 1;
    
    for(int i = 0; i < sizeof(int)*8; i++) {
    
        /* If result of operating is equal one, resule increase */
        if (x_y_xor & bitcheck)
            result++;
        bitcheck = bitcheck << 1;
    }
    
    return result;
}

int main()
{
    int input1 = 51;
    int input2 = 23;
    
    printf("Result = %d",hammingDistance(input1, input2));
    return 0;
}
```