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
5in binary is101 - Flipping the bits gives us
010 - Which equals
2in 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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code