๐ One-stop destination for all your technical interview Preparation ๐
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.
N is the number of bits in the given input numbersclass Solution {
public:
int hammingDistance(int x, int y) {
bitset<32> xb(x), yb(y);
int ans = 0;
for(int i = 0; i < 32; i++)
ans += (xb[i] != yb[i]);
return ans;
}
};
ith bit of a number x is set, we can perform - (x >> i) & 1.class Solution {
public:
int hammingDistance(int x, int y) {
int ans = 0;
for(int i = 0; i < 32; i++)
ans += ((x >> i & 1) != (y >> i & 1));
return ans;
}
};
ans = bitset<32>(Xor).count()
ans = __builtin_popcount(Xor);
ans = popcount(Xor) // only since C++20
class Solution {
public:
int hammingDistance(int x, int y) {
int Xor = x ^ y, ans = 0;
for(int i = 0; i < 32; i++)
ans += ((Xor & (1 << i)) != 0);
return ans;
}
};
n & (n - 1) until xor becomes 0 and increment the count each time.class Solution {
public:
int hammingDistance(int x, int y) {
int XOR = x ^ y, ans = 0;
while(XOR) {
XOR &= XOR-1; // n&(n-1) clears the rightmost set bit
ans++;
}
return ans;
}
};
N for this problem is fixed to 32. So, strictly speaking, the time complexity of 1st three solutions is O(N) = O(32) = O(1). But to differentiate between time complexities of 1st three and last approach, I have denoted them as O(N).