Build an all-ones mask covering the number's significant bits and XOR it with the number, treating zero as a one-bit value.
Complexity
O(log n) time and O(1) space.
Flip every significant bit in a nonnegative integer's binary representation.
Build an all-ones mask covering the number's significant bits and XOR it with the number, treating zero as a one-bit value.
O(log n) time and O(1) space.
package main
func bitwiseComplement(n int) int {
if n == 0 {
return 1
}
mask := 1
for mask <= n {
mask <<= 1
}
return (mask - 1) ^ n
}
class Solution:
def bitwiseComplement(self, n: int) -> int:
if n == 0: return 1
mask = 1
while mask <= n: mask <<= 1
return (mask - 1) ^ n
function bitwiseComplement(n: number): number {
if (n === 0) return 1;
let mask = 1;
while (mask <= n) mask <<= 1;
return (mask - 1) ^ n;
}