Complement of Base 10 Integer - 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 n, return its complement.
Input & Output
Example 1 — Basic Case
$
Input:
n = 5
›
Output:
2
💡 Note:
5 in binary is 101. Flipping all bits gives 010, which is 2 in decimal.
Example 2 — Single Bit
$
Input:
n = 1
›
Output:
0
💡 Note:
1 in binary is 1. Flipping the bit gives 0.
Example 3 — Power of Two
$
Input:
n = 4
›
Output:
3
💡 Note:
4 in binary is 100. Flipping all bits gives 011, which is 3 in decimal.
Constraints
- 1 ≤ n ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Integer n = 5 (binary: 101)
2
Process
Flip all bits: 0→1, 1→0
3
Output
Result = 2 (binary: 010)
Key Takeaway
🎯 Key Insight: XOR with a mask of all 1's flips every bit efficiently in O(1) time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code