Leetcode 461. Hamming Distance
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 (in binary): 0001
4 (in binary): 0100
The Hamming distance is 2 because there are two positions at which the corresponding bits are different.
^) between two bits results in 1 if the bits are different and 0 if they are the same. Thus, XORing the two numbers will result in a number whose binary representation has 1s in positions where the corresponding bits of the original numbers differ.1s in this resultant number. This can be done using bit manipulation techniques or using built-in functions.#include <iostream>
using namespace std;
int hammingDistance(int x, int y) {
int xor_val = x ^ y;
int distance = 0;
while (xor_val > 0) {
if (xor_val & 1) {
distance++;
}
xor_val >>= 1;
}
return distance;
}
int main() {
int x = 1;
int y = 4;
cout << "Hamming Distance between " << x << " and " << y << " is " << hammingDistance(x, y) << endl;
return 0;
}
x and y is computed with int xor_val = x ^ y;.distance to 0. While xor_val is greater than 0, check the least significant bit (LSB) using xor_val & 1. If the LSB is 1, increment the distance. Shift xor_val right by one bit (xor_val >>= 1;) and continue until all bits are checked.O(1) because, in the worst case, you would perform a constant number of operations (32 for a 32-bit number). Each bit is checked and counted only once.The space complexity is O(1) as only a few integer variables are used, independent of the input values.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?