#1009

Complement of Base 10 Integer

Easy Bit masks

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Flip every bit of n's binary form (only the bits that are actually used, no leading zeros) and return the result. For example 5 = 101 becomes 010 = 2.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: flip only the bits that are actually used, not the leading zeros.

Why this works: XOR with a mask of all 1s of the same length flips exactly those bits.

Example: n = 5 (101)

mask grows 1 → 11 → 111101 ^ 111 = 010 → 2

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Returning ~n, which gives a negative number.