Merge pull request #336 from SaurusXI/master

Added commented solution to problem 461
This commit is contained in:
Hai Hoang Dang 2019-10-04 19:01:47 -07:00 committed by GitHub
commit 26ff845615
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 0 deletions

View File

@ -48,6 +48,7 @@ LeetCode
|389|[Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C](./src/389.c)|Easy|
|404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C](./src/404.c)|Easy|
|442|[Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [C](./src/442.c)|Medium|
|461|[Hamming Distance](https://leetcode.com/problems/hamming-distance/) | [C](./src/461.c) |Easy|
|509|[Fibonacci Number](https://leetcode.com/problems/fibonacci-number/) | [C](./src/509.c)|Easy|
|520|[Detect Capital](https://leetcode.com/problems/detect-capital/) | [C](./src/520.c)|Easy|
|561|[Array Partition I](https://leetcode.com/problems/array-partition-i/) | [C](./src/561.c)|Easy|

12
leetcode/src/461.c Normal file
View File

@ -0,0 +1,12 @@
int hammingDistance(int x, int y){
int difference = x ^ y; //The XOR operator generates the bitwise difference in the binary representation of two numbers
//If bit in ith position of both numbers is same, bit in difference is 0, otherwise 1
int TotalBits = sizeof(difference)*8; //total number of bits
int i, distance = 0;
for(i = 0; i < TotalBits; i++) {
if(difference & (UINT32_C(1) << i)) //if the bit on the ith position of 32 bit input is 1, then proceed
//Further note the use of UINT32_C to convert 1 to unsigned 32 bit int, as just 1 is treated as int which cannot be shifted left more than 30 times
distance += 1;
}
return distance;
}