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
Complement of Base 10 Integer: Flip All BitsInput: 5Binary: 1013 bitsOriginal NumberFLIPBit Flipping ProcessOriginal: 1 0 1Flip: ↓ ↓ ↓Result: 0 1 0Transform Each BitOutput: 2Binary: 010Same lengthComplement Result🎯 Key InsightXOR with mask of all 1s flips every significant bit perfectly!
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
Asked in
Google 15 Amazon 12 Apple 8 Microsoft 10
85.0K Views
Medium Frequency
~15 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