diff --git a/leetcode/README.md b/leetcode/README.md index 1718af9d..9c8402df 100644 --- a/leetcode/README.md +++ b/leetcode/README.md @@ -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| diff --git a/leetcode/src/476.c b/leetcode/src/476.c new file mode 100644 index 00000000..f6ee952f --- /dev/null +++ b/leetcode/src/476.c @@ -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; +} \ No newline at end of file