Complement of Base 10 Integer - Problem

Ever wondered what happens when you flip every bit in a number's binary representation? That's exactly what we're doing in this fascinating bit manipulation problem!

The Challenge: Given an integer n, find its complement by flipping all the bits in its binary representation. This means every 0 becomes a 1, and every 1 becomes a 0.

Key Examples:

  • The number 5 in binary is 101
  • Flipping the bits gives us 010
  • Which equals 2 in decimal

Important Note: We only consider the significant bits (no leading zeros in the original number). For example, 5 is represented as 101, not 00000101.

Goal: Return the decimal value of the complement.

Input & Output

example_1.py โ€” Simple Case
$ Input: n = 5
โ€บ Output: 2
๐Ÿ’ก Note: 5 in binary is 101. The complement flips all bits: 101 โ†’ 010, which equals 2 in decimal.
example_2.py โ€” Single Bit
$ Input: n = 1
โ€บ Output: 0
๐Ÿ’ก Note: 1 in binary is 1. The complement flips the single bit: 1 โ†’ 0, which equals 0 in decimal.
example_3.py โ€” Power of 2 Minus 1
$ Input: n = 7
โ€บ Output: 0
๐Ÿ’ก Note: 7 in binary is 111. The complement flips all bits: 111 โ†’ 000, which equals 0 in decimal.

Constraints

  • 1 โ‰ค n โ‰ค 231 - 1
  • The input is guaranteed to be a positive integer
  • No leading zeros in the binary representation

Visualization

Tap to expand
Binary Complement: The Light Switch AnalogyOriginal State (Number 5)ON1OFF0ON1Master Switch (XOR Mask)XOR111Result State (Number 2)OFF0ON1OFF0Step-by-Step Process:1. Input: n = 5 (binary: 101)2. Find bit length: 3 bits3. Create mask: (1 << 3) - 1 = 7 (binary: 111)4. XOR operation: 101 โŠ• 111 = 0105. Result: 010 = 2 (decimal)Truth Table for XOROriginal | Mask | Result1 | 1 | 00 | 1 | 11 | 1 | 0โ† Flippedโ† Flippedโ† Flipped
Understanding the Visualization
1
Identify Pattern
Recognize that we need to flip exactly the significant bits
2
Create Mask
Build a mask with 1s in all positions we want to flip
3
Apply XOR
Use XOR operation to flip all bits simultaneously
4
Get Result
The XOR result is our complement
Key Takeaway
๐ŸŽฏ Key Insight: The XOR operation with a carefully crafted mask flips exactly the bits we want - it's like having a master switch that controls all the individual switches at once!
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
89.6K Views
Medium Frequency
~8 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen