Number Complement - Problem
Binary Number Complement Challenge
In the world of binary operations, every number has an alter ego - its complement! Your mission is to find this binary opposite.
Given an integer
โข Convert all
โข Convert all
Example: The number
Note: We only consider the significant bits (ignore leading zeros in the original number).
In the world of binary operations, every number has an alter ego - its complement! Your mission is to find this binary opposite.
Given an integer
num, you need to flip every bit in its binary representation:โข Convert all
0s to 1sโข Convert all
1s to 0sExample: The number
5 in binary is 101. Flipping the bits gives us 010, which equals 2 in decimal.Note: We only consider the significant bits (ignore leading zeros in the original number).
Input & Output
example_1.py โ Basic Case
$
Input:
num = 5
โบ
Output:
2
๐ก Note:
The binary representation of 5 is 101 (in binary). The complement flips all bits: 101 โ 010, which equals 2 in decimal.
example_2.py โ Single Bit
$
Input:
num = 1
โบ
Output:
0
๐ก Note:
The binary representation of 1 is 1 (in binary). The complement flips the single bit: 1 โ 0, which equals 0 in decimal.
example_3.py โ Larger Number
$
Input:
num = 7
โบ
Output:
0
๐ก Note:
The binary representation of 7 is 111 (in binary). The complement flips all bits: 111 โ 000, which equals 0 in decimal.
Constraints
- 1 โค num โค 231 - 1
- The input is guaranteed to be a positive integer
- Only consider the significant bits (no leading zeros)
Visualization
Tap to expand
Understanding the Visualization
1
Identify Bit Pattern
Look at the binary representation of the input number
2
Create Universal Flipper
Make a mask with all 1s that covers exactly the same bit positions
3
Flip All Switches
XOR the number with the mask to flip every bit simultaneously
Key Takeaway
๐ฏ Key Insight: XOR with a mask of all 1s efficiently flips every bit in the significant portion of the number
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code