Hamming distance between two Integers
Last Updated :
11 Jul, 2025
Given two integers, the task is to find the hamming distance between two integers. Hamming Distance between two integers is the number of bits that are different at the same position in both numbers.
Examples:
Input: n1 = 9, n2 = 14
Output: 3
9 = 1001, 14 = 1110
No. of Different bits = 3
Input: n1 = 4, n2 = 8
Output: 2
Approach:
- Calculate the XOR of two numbers.
- Count the number of set bits.
Below is the implementation of above approach:
C++
// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
// Function to calculate hamming distance
int hammingDistance(int n1, int n2)
{
int x = n1 ^ n2;
int setBits = 0;
while (x > 0) {
setBits += x & 1;
x >>= 1;
}
return setBits;
}
// Driver code
int main()
{
int n1 = 9, n2 = 14;
cout << hammingDistance(9, 14) << endl;
return 0;
}
// This code is contributed by Sania Kumari Gupta (kriSania804)
C
// C implementation of above approach
#include <stdio.h>
// Function to calculate hamming distance
int hammingDistance(int n1, int n2)
{
int x = n1 ^ n2;
int setBits = 0;
while (x > 0) {
setBits += x & 1;
x >>= 1;
}
return setBits;
}
// Driver code
int main()
{
int n1 = 9, n2 = 14;
printf("%d\n", hammingDistance(9, 14));
return 0;
}
// This code is contributed by Sania Kumari Gupta (kriSania804)
Java
// Java implementation of above approach
class GFG
{
// Function to calculate hamming distance
static int hammingDistance(int n1, int n2)
{
int x = n1 ^ n2;
int setBits = 0;
while (x > 0)
{
setBits += x & 1;
x >>= 1;
}
return setBits;
}
// Driver code
public static void main(String[] args)
{
int n1 = 9, n2 = 14;
System.out.println(hammingDistance(n1, n2));
}
}
// This code is contributed by Bilal
Python3
# Python3 implementation of above approach
# Function to calculate hamming distance
def hammingDistance(n1, n2) :
x = n1 ^ n2
setBits = 0
while (x > 0) :
setBits += x & 1
x >>= 1
return setBits
if __name__=='__main__':
n1 = 9
n2 = 14
print(hammingDistance(9, 14))
# this code is contributed by Smitha Dinesh Semwal
C#
// C# implementation of above approach
class GFG
{
// Function to calculate
// hamming distance
static int hammingDistance(int n1, int n2)
{
int x = n1 ^ n2;
int setBits = 0;
while (x > 0)
{
setBits += x & 1;
x >>= 1;
}
return setBits;
}
// Driver code
static void Main()
{
int n1 = 9, n2 = 14;
System.Console.WriteLine(hammingDistance(n1, n2));
}
}
// This code is contributed by mits
JavaScript
<script>
// Javascript implementation of above approach
// Function to calculate hamming distance
function hammingDistance(n1, n2)
{
let x = n1 ^ n2;
let setBits = 0;
while (x > 0) {
setBits += x & 1;
x >>= 1;
}
return setBits;
}
// Driver code
let n1 = 9, n2 = 14;
document.write(hammingDistance(9, 14));
</script>
PHP
<?PHP
// PHP implementation of above approach
// Function to calculate hamming distance
function hammingDistance($n1, $n2)
{
$x = $n1 ^ $n2;
$setBits = 0;
while ($x > 0)
{
$setBits += $x & 1;
$x >>= 1;
}
return $setBits;
}
// Driver code
$n1 = 9;
$n2 = 14;
echo(hammingDistance(9, 14));
// This code is contributed by Smitha
?>
Note: No. of set bits can be counted using __builtin_popcount() function.
Time Complexity: O(log2x), where x is n1 ^ n2, this can be interpreted as O(1), since an int can hold a maximum of 32 bits
Auxiliary Space: O(1)
Approach 2:
1. Calculate the maximum of both numbers.
2. Check the set bits for both at each position.
C++
#include <bits/stdc++.h>
using namespace std;
int hammingDistance(int x, int y)
{
int ans = 0;
int m = max(x, y);
while (m) {
int c1 = x & 1;
int c2 = y & 1;
if (c1 != c2)
ans += 1;
m = m >> 1;
x = x >> 1;
y = y >> 1;
}
return ans;
}
int main()
{
int n1 = 4, n2 = 8;
int hdist = hammingDistance(n1, n2);
cout << hdist << endl;
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
static int hammingDistance(int x, int y)
{
int ans = 0;
int m = Math.max(x, y);
while (m>0) {
int c1 = x & 1;
int c2 = y & 1;
if (c1 != c2)
ans += 1;
m = m >> 1;
x = x >> 1;
y = y >> 1;
}
return ans;
}
// Drivers code
public static void main(String args[])
{
int n1 = 4, n2 = 8;
int hdist = hammingDistance(n1, n2);
System.out.println(hdist);
}
}
// This code is contributed by shinjanpatra
Python3
# Python3 code for the same approach
def hammingDistance(x, y):
ans = 0
m = max(x, y)
while (m):
c1 = x & 1
c2 = y & 1
if (c1 != c2):
ans += 1
m = m >> 1
x = x >> 1
y = y >> 1
return ans
# driver program
n1 = 4
n2 = 8
hdist = hammingDistance(n1, n2)
print(hdist)
# This code is contributed by shinjanpatra
C#
// C# code to implement the approach
using System;
public class GFG
{
// Function that return the hamming distance
// between x and y
static int hammingDistance(int x, int y)
{
int ans = 0;
int m = Math.Max(x, y);
// checking the set bits
while (m > 0) {
int c1 = x & 1;
int c2 = y & 1;
if (c1 != c2)
ans += 1;
m = m >> 1;
x = x >> 1;
y = y >> 1;
}
return ans;
}
// Driver code
public static void Main(string[] args)
{
int n1 = 4, n2 = 8;
// Function call
int hdist = hammingDistance(n1, n2);
Console.WriteLine(hdist);
}
}
// This code is contributed by phasing17
JavaScript
<script>
// JavaScript code for the same approach
function hammingDistance(x,y)
{
let ans = 0;
let m = Math.max(x, y);
while (m) {
let c1 = x & 1;
let c2 = y & 1;
if (c1 != c2)
ans += 1;
m = m >> 1;
x = x >> 1;
y = y >> 1;
}
return ans;
}
// driver program
let n1 = 4,n2 = 8;
let hdist = hammingDistance(n1, n2);
document.write(hdist,"</br>");
// This code is contributed by shinjanpatra
</script>
Time Complexity: O(log2(max(n1, n2)).
Auxiliary Space: O(1)
Approach#3: Using string manipulation
Algorithm
1. Convert the two given integers to binary strings.
2. Pad the shorter binary string with leading zeros to make both strings of equal length.
3. Compare the two binary strings bit by bit and count the number of differences.
4. The count obtained in step 3 represents the Hamming distance between the two given integers.
C++
// c++ code implementation
#include <iostream>
#include <bitset>
#include <string>
using namespace std;
int hammingDistance(int n1, int n2) {
string binStr1 = bitset<32>(n1).to_string();
string binStr2 = bitset<32>(n2).to_string();
int lenDiff = abs(static_cast<int>(binStr1.length() - binStr2.length()));
if (binStr1.length() < binStr2.length()) {
binStr1 = string(lenDiff, '0') + binStr1;
} else {
binStr2 = string(lenDiff, '0') + binStr2;
}
int count = 0;
for (int i = 0; i < binStr1.length(); i++) {
if (binStr1[i] != binStr2[i]) {
count++;
}
}
return count;
}
int main() {
int n1 = 4;
int n2 = 8;
cout << hammingDistance(n1, n2) << endl;
return 0;
}
Java
public class Main {
public static int hammingDistance(int n1, int n2) {
String binStr1 = Integer.toBinaryString(n1);
String binStr2 = Integer.toBinaryString(n2);
int lenDiff = Math.abs(binStr1.length() - binStr2.length());
if (binStr1.length() < binStr2.length()) {
binStr1 = "0".repeat(lenDiff) + binStr1;
} else {
binStr2 = "0".repeat(lenDiff) + binStr2;
}
int count = 0;
for (int i = 0; i < binStr1.length(); i++) {
if (binStr1.charAt(i) != binStr2.charAt(i)) {
count++;
}
}
return count;
}
public static void main(String[] args) {
int n1 = 4;
int n2 = 8;
System.out.println(hammingDistance(n1, n2));
}
}
Python3
def hamming_distance(n1, n2):
bin_str1 = bin(n1)[2:]
bin_str2 = bin(n2)[2:]
len_diff = abs(len(bin_str1) - len(bin_str2))
if len(bin_str1) < len(bin_str2):
bin_str1 = '0' * len_diff + bin_str1
else:
bin_str2 = '0' * len_diff + bin_str2
count = 0
for i in range(len(bin_str1)):
if bin_str1[i] != bin_str2[i]:
count += 1
return count
n1 = 4
n2 = 8
print(hamming_distance(n1, n2))
C#
// C# code to implement the approach
using System;
public class Gfg
{
// Function to calculate Hamming distance between two integers
public static int HammingDistance(int n1, int n2)
{
// Convert integers to binary strings
string binStr1 = Convert.ToString(n1, 2);
string binStr2 = Convert.ToString(n2, 2);
// Calculate the absolute difference in binary string lengths
int lenDiff = Math.Abs(binStr1.Length - binStr2.Length);
// Ensure that both binary strings have
// the same length by adding leading zeros
if (binStr1.Length < binStr2.Length)
{
binStr1 = new string('0', lenDiff) + binStr1;
}
else
{
binStr2 = new string('0', lenDiff) + binStr2;
}
int count = 0;
// Iterate through the binary strings and count differing bits
for (int i = 0; i < binStr1.Length; i++)
{
if (binStr1[i] != binStr2[i])
{
count++;
}
}
return count;
}
// Driver Code
public static void Main()
{
int n1 = 4;
int n2 = 8;
Console.WriteLine(HammingDistance(n1, n2));
}
}
// This code is contributed by Pushpesh Raj
JavaScript
function hamming_distance(n1, n2) {
let bin_str1 = n1.toString(2);
let bin_str2 = n2.toString(2);
let len_diff = Math.abs(bin_str1.length - bin_str2.length);
if (bin_str1.length < bin_str2.length) {
bin_str1 = '0'.repeat(len_diff) + bin_str1;
} else {
bin_str2 = '0'.repeat(len_diff) + bin_str2;
}
let count = 0;
for (let i = 0; i < bin_str1.length; i++) {
if (bin_str1[i] !== bin_str2[i]) {
count += 1;
}
}
return count;
}
let n1 = 4;
let n2 = 8;
console.log(hamming_distance(n1, n2));
Time Complexity: O(log n), where n is the maximum of the two integers.
Space Complexity: O(log n), where n is the maximum of the two integers.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem