mirror of
https://github.com/Manoj-HV30/dsa-competitive-programming.git
synced 2026-05-16 19:35:22 +00:00
added cses
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
class Solution{
|
||||
public :
|
||||
int bitwiseComplement(int n ){
|
||||
if(n==0) return 1;
|
||||
short c = bit_width(static_cast<unsigned int>(n));
|
||||
int x = (1<<c) -1;
|
||||
return ~n&x;
|
||||
|
||||
}
|
||||
};
|
||||
/*
|
||||
Idea:
|
||||
Flip only the bits used in n's binary representation.
|
||||
|
||||
1. Find number of bits in n using:
|
||||
std::bit_width(n)
|
||||
It returns how many bits are needed to represent n.
|
||||
|
||||
2. Create a mask with all those bits set to 1:
|
||||
mask = (1 << bit_width) - 1
|
||||
Example: bit_width = 3 -> mask = 111
|
||||
|
||||
3. Flip n using ~n, then remove extra leading 1s:
|
||||
result = (~n) & mask
|
||||
|
||||
Special case: n = 0 -> answer = 1
|
||||
*/
|
||||
Reference in New Issue
Block a user