Skip to content

Commit f603e21

Browse files
committed
Added hamming distance program
1 parent 8e7b05f commit f603e21

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,8 @@ Include contains single header implementation of data structures and some algori
226226
| Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. Ensure that numbers within the set are sorted in ascending order. Example : for k = 3, n = 9 result would be [[1,2,6], [1,3,5], [2,3,4]], similarly for k = 3, n = 7, result would be [[1,2,4]]. | [combinationSum3.cpp](leet_code_problems/combinationSum3.cpp) |
227227
| Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. Follow up: Could you do it without any loop/recursion in O(1) runtime?| [addDigits.cpp](leet_code_problems/addDigits.cpp) |
228228
| Given a matrix with cell values 0 or 1. Find the length of the shortest path from (a1, b1) to (a2, b2), such that path can only be constructed through cells which have value 1 and you can only travel in 4 possible directions, i.e. left, right, up and down.|[shortest_path_maze.cpp](leet_code_problems/shortest_path_maze.cpp) |
229-
229+
| The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
230+
Given two integers x and y, calculate the Hamming distance.| [hamming_distance.cpp](leet_code_problems/hamming_distance.cpp)|
230231

231232

232233

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
The Hamming distance between two integers is the number of positions at which
3+
the corresponding bits are different.
4+
Given two integers x and y, calculate the Hamming distance.
5+
6+
Input: x = 1, y = 4
7+
8+
Output: 2
9+
10+
Explanation:
11+
1 (0 0 0 1)
12+
4 (0 1 0 0)
13+
↑ ↑
14+
15+
The above arrows point to positions where the corresponding bits are different
16+
*/
17+
18+
#include <iostream>
19+
20+
int hamming_distance(int x, int y)
21+
{
22+
// XOR will set only those bits in z which are different in x and y
23+
int z = x ^ y;
24+
25+
// Now just count set bits in z.
26+
int count = 0;
27+
while (z)
28+
{
29+
count += (z % 2);
30+
z >>= 2;
31+
}
32+
return count;
33+
}
34+
35+
36+
int main()
37+
{
38+
int x = 4;
39+
int y = 1;
40+
std::cout << "Hamming distance between " << x << " and " << y << " is : "
41+
<< hamming_distance(x, y) << std::endl;
42+
}

0 commit comments

Comments
 (0)