Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created March 11, 2026 18:56
Show Gist options
  • Select an option

  • Save tatsuyax25/865f394b1feb5f283c6499ecb6fba779 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/865f394b1feb5f283c6499ecb6fba779 to your computer and use it in GitHub Desktop.
The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation. For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2. Given an inte
/**
* @param {number} n
* @return {number}
*/
/**
* @param {number} n
* @return {number}
*/
var bitwiseComplement = function(n) {
// Edge case:
// LeetCode defines the complement of 0 as 1.
// Binary: "0" → flip → "1"
if (n === 0) return 1;
// We want to build a mask of all 1s that covers
// exactly the bit-length of n.
//
// Example: n = 10 (1010)
// mask should become 1111 (binary) = 15
//
// Start mask at 1 (binary: 1)
let mask = 1;
// Keep expanding mask by shifting left and adding 1:
// 1 -> 1
// 1<<1|1 -> 3 (11)
// 3<<1|1 -> 7 (111)
// 7<<1|1 -> 15 (1111)
//
// Stop once mask is >= n.
while (mask < n) {
mask = (mask << 1) | 1;
}
// XOR with mask flips all bits of n within the mask range.
// Example:
// n = 1010 (10)
// mask = 1111 (15)
// XOR = 0101 (5)
return mask ^ n;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment