Number Complement - Problem
The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.
For example, the integer 5 is "101" in binary and its complement is "010" which is the integer 2.
Given an integer num, return its complement.
Input & Output
Example 1 — Basic Case
$
Input:
num = 5
›
Output:
2
💡 Note:
5 in binary is 101. Flipping each bit: 1→0, 0→1, 1→0 gives us 010, which is 2 in decimal.
Example 2 — Single Bit
$
Input:
num = 1
›
Output:
0
💡 Note:
1 in binary is 1. Flipping the bit: 1→0 gives us 0.
Example 3 — Larger Number
$
Input:
num = 7
›
Output:
0
💡 Note:
7 in binary is 111. Flipping each bit: 1→0, 1→0, 1→0 gives us 000, which is 0 in decimal.
Constraints
- 1 ≤ num ≤ 231 - 1
Visualization
Tap to expand
Understanding the Visualization
1
Input Number
Given number 5 with binary representation 101
2
Flip All Bits
Change each 1 to 0 and each 0 to 1
3
Output Complement
Result is 010 in binary, which equals 2 in decimal
Key Takeaway
🎯 Key Insight: XOR with a mask of all 1's efficiently flips every bit in the number
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code