#1009

Complement of Base 10 Integer

Easy
Bit ManipulationBit ManipulationMasking
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(1)
Space
O(n)
O(1)
💡

Intuition

Time O(1)Space O(1)

The optimal solution leverages the property that the complement of a number plus the number itself equals a number with all bits set to 1. By calculating this directly, we avoid unnecessary conversions.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the bit length of n to determine how many bits are needed.
  2. 2Step 2: Create a mask with all bits set to 1 for the length of n.
  3. 3Step 3: Subtract n from the mask to get the complement.
solution.py3 lines
1def findComplement(n):
2    mask = (1 << n.bit_length()) - 1
3    return mask - n

Complexity note: The time complexity is O(1) because it involves constant time operations regardless of the size of n. The space complexity is also O(1) since we are using a fixed amount of space.

  • 1The complement operation is closely related to binary representation and bit manipulation.
  • 2Understanding how to create a mask can simplify many problems involving binary operations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.