Isaac Emmanuel
09 Sept 2026•EasyGo / Python / TypeScript

Complement of Base 10 Integer

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.

Complexity

O(log n) time and O(1) space.

Solution files

Go•complement-of-base-10-integer/solution.go
package main

func bitwiseComplement(n int) int {
	if n == 0 {
		return 1
	}
	mask := 1
	for mask <= n {
		mask <<= 1
	}
	return (mask - 1) ^ n
}
Python•complement-of-base-10-integer/solution.py
class Solution:
    def bitwiseComplement(self, n: int) -> int:
        if n == 0: return 1
        mask = 1
        while mask <= n: mask <<= 1
        return (mask - 1) ^ n
TypeScript•complement-of-base-10-integer/solution.ts
function bitwiseComplement(n: number): number {
  if (n === 0) return 1;
  let mask = 1;
  while (mask <= n) mask <<= 1;
  return (mask - 1) ^ n;
}