mirror of
https://github.moeyy.xyz/https://github.com/TheAlgorithms/C.git
synced 2023-10-11 15:56:24 +08:00
Merge pull request #339 from SaurusXI/master
Added commented solution to Leetcode problem 476
This commit is contained in:
commit
f063b030f8
@ -49,6 +49,7 @@ LeetCode
|
||||
|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|
|
||||
|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|
|
||||
|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|
|
||||
|
15
leetcode/src/476.c
Normal file
15
leetcode/src/476.c
Normal 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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user