Search⌘ K

Hamming Distance

Explore how to find the Hamming Distance between two integers by identifying differing bits. Understand bit shifting and Brian Kernighan’s algorithm to solve the problem efficiently with constant time and space complexity.

Introduction

In this question, we will find the number of positions at which the corresponding bits are different.

Problem Statement

Given integers x, y finds the positions where the corresponding bits are different.

Input: x = 1, y = 8
Output: 2
Explanation:
1   (0 0 0 1)
8   (1 0 0 0)
     ↑     ↑
Input: x = 12, y = 15
Output: 2
Explanation:
12   (1 1 0 0)
15   (1 1 1 1)
          ↑ ↑
...