
Sponsored
Sponsored
This approach uses bit manipulation to find the complement. The idea is to create a mask that has the same number of bits set to 1 as the number. By XORing the number with this mask, we effectively flip all the bits.
To create the mask, we can shift 1 left until it exceeds the number and then subtract 1 from it.
Time Complexity: O(1), the operations are done in constant time as the number of bits is fixed.
Space Complexity: O(1), no additional space is used.
1using System;
2
3class Program {
4 public static int FindComplement(int num) {
5 int mask = ~0;
6 while ((num & mask) != 0) mask <<= 1;
7 return ~mask & ~num;
8 }
9
10 static void Main() {
11 Console.WriteLine(FindComplement(5)); // Output: 2
12 Console.WriteLine(FindComplement(1)); // Output: 0
13 }
14}The C# solution uses a bit manipulation strategy similar to C/C++. We use the bitwise mask to XOR the negation of the number to get its complement.
This approach derives a mask by using the bit length of the number. We create a mask by taking 2n - 1, where n is the bit size of the number.
The result of the XOR between num and mask gives the complement.
Time Complexity: O(1)
Space Complexity: O(1)
1def
This Python function computes the mask based on the input's bit length, then returns the complement by XORing.