461. Hamming Distance
Yet another example of the bitwise XOR operator

Hi! My name is Nhut Nguyen. I am a software engineer and a writer in Copenhagen, Denmark.
Learn more about me at nhutnguyen.com
Search for a command to run...
Yet another example of the bitwise XOR operator

Hi! My name is Nhut Nguyen. I am a software engineer and a writer in Copenhagen, Denmark.
Learn more about me at nhutnguyen.com
No comments yet. Be the first to comment.
A simple example of using C++ switch

Two dynamic programming techniques to solve Leetcode 120. Triangle. One has space complexity O(n^2). The other is O(n).

An example of using a sliding window approach and an unordered map to track character positions

A simple C++ solution to Leetcode 1695. Maximum Erasure Value using a sliding window approach and prefix sums.

Strategies to avoid them will help you excel in your following technical interview

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, return the Hamming distance between them.
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.
Input: x = 3, y = 1
Output: 1
0 <= x, y <= 2^31.You could use bit operator ^ (XOR) to get the bit positions where x and y are different. Then use bit operator & (AND) at each position to count them.
#include <iostream>
int hammingDistance(int x, int y) {
int z = x ^ y;
int count = 0;
while (z) {
count += z & 1;
z = z >> 1;
}
return count;
}
int main() {
std::cout << hammingDistance(1,4) << std::endl;
std::cout << hammingDistance(1,3) << std::endl;
}
Output:
2
1
Runtime: O(1).
Extra space: O(1).
Thanks for reading. Feel free to share your thought about my content and check out my FREE book “10 Classic Coding Challenges”.