
Sponsored
Sponsored
This approach involves calculating a mask of the same bit length as the number and then using XOR to flip all the bits. The mask is calculated as a sequence of 1s of the same length as the binary representation of the number. For any number 'n', the mask would be computed as (1 << number_of_bits) - 1.
Time Complexity: O(log(n)) as we are shifting bits for the length of the number.
Space Complexity: O(1) since we are using a constant space.
1using System;
2
3public class Solution {
4 public int BitwiseComplement(int n) {
5 if (n == 0) return 1;
6 int mask = 0;
7 int m = n;
8 while (m != 0) {
9 mask = (mask << 1) | 1;
10 m >>= 1;
11 }
12 return (~n) & mask;
13 }
14
15 public static void Main(string[] args) {
16 Solution sol = new Solution();
17 int n = 5;
18 Console.WriteLine(sol.BitwiseComplement(n));
19 }
20}This C# implementation matches the logic seen in other languages, leveraging bit shifting and masks to maintain a concise complement computation that is efficient.
In this approach, instead of calculating a mask using shifts, we use mathematical expressions. We calculate the highest power of 2 greater than n, subtract 1 to get a mask with all 1s up to the highest bit set in n. This mask is then XORed with n for the result.
Time Complexity: O(log(n)) for shifting mask while determining the next power of 2.
Space Complexity: O(1) as only simple variables are used.
1
public class Solution {
public int BitwiseComplement(int n) {
if (n == 0) return 1;
int mask = 1;
while (mask <= n) mask <<= 1;
return (mask - 1) ^ n;
}
public static void Main(string[] args) {
Solution sol = new Solution();
int n = 5;
Console.WriteLine(sol.BitwiseComplement(n));
}
}The solution in C# is effectively identical to other language implementations, reflecting efficiency by leveraging mathematical insights to achieve correct complementary operations.