Merge pull request #339 from SaurusXI/master

Added commented solution to Leetcode problem 476
This commit is contained in:
Hai Hoang Dang 2019-10-05 10:43:42 -07:00 committed by GitHub
commit f063b030f8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 0 deletions

View File

@ -49,6 +49,7 @@ LeetCode
|404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C](./src/404.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| |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| |461|[Hamming Distance](https://leetcode.com/problems/hamming-distance/) | [C](./src/461.c) |Easy|
|476|[Number Complement](https://leetcode.com/problems/number-complement/) | [C](./src/476.c)|Easy|
|509|[Fibonacci Number](https://leetcode.com/problems/fibonacci-number/) | [C](./src/509.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| |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| |561|[Array Partition I](https://leetcode.com/problems/array-partition-i/) | [C](./src/561.c)|Easy|

15
leetcode/src/476.c Normal file
View File

@ -0,0 +1,15 @@
int findComplement(int num) {
int TotalBits = 0;
int temp = num;
while(temp) { //To find position of MSB in given num. Since num is represented as a standard size in memory, we cannot rely on size
//for that information.
TotalBits++; //increment TotalBits till temp becomes 0
temp >>= 1; //shift temp right by 1 bit every iteration; temp loses 1 bit to underflow every iteration till it becomes 0
}
int i, flipNumber = 1; //Eg: 1's complement of 101(binary) can be found as 101^111 (XOR with 111 flips all bits that are 1 to 0 and flips 0 to 1)
for(i = 1; i < TotalBits; i++) {
flipNumber += UINT32_C(1) << i; //Note the use of unsigned int to facilitate left shift more than 31 times, if needed
}
num = num^flipNumber;
return num;
}