Teaching Kids Programming – Compute the Hamming Distance of Two Integers


Teaching Kids Programming: Videos on Data Structures and Algorithms

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.

Compute the Hamming Distance

The XOR of two integers, will set 1 to those bits of different values. Thus, we can use XOR and count the value of 1’s bits: Teaching Kids Programming – Compute the Number of Set Bits in an Integer

1
2
3
4
5
6
7
8
class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        n = x ^ y
        a = 0
        while n > 0:
            a += 1
            n &= (n - 1)
        return a
class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        n = x ^ y
        a = 0
        while n > 0:
            a += 1
            n &= (n - 1)
        return a

Hamming Weight / Hamming Distance Algorithms

Here are the posts related to Hamming Distance (XOR, The number of different bits):

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
531 words
Last Post: Teaching Kids Programming - Python Function to Check If Valid IPv4 Address
Next Post: K Distinct Window Algorithm by Sliding Window

The Permanent URL is: Teaching Kids Programming – Compute the Hamming Distance of Two Integers

Leave a Reply