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 INPUT Decimal Number n = 5 Binary Representation 1 0 1 2^2 2^1 2^0 Input Value 5 = "101" in binary 4 + 0 + 1 = 5 (1*4 + 0*2 + 1*1) ALGORITHM STEPS 1 Find Bit Length Count bits in n (3 bits) 2 Create Bit Mask mask = (1 << 3) - 1 = 7 3 XOR with Mask result = n XOR mask 4 Return Result 5 XOR 7 = 2 XOR Operation Detail n = 101 (5) mask = 111 (7) XOR = 010 (2) Flip: 1-->0, 0-->1, 1-->0 FINAL RESULT Complement Binary 0 1 0 1-->0 0-->1 1-->0 Decimal Result 2 Output Value "010" = 2 (decimal) OK - Verified Key Insight: XOR with a mask of all 1s (same bit length) flips every bit efficiently in O(1) time. The mask is created using (1 << bitLength) - 1, which gives all 1s for the required bits. Example: For 3 bits, mask = (1 << 3) - 1 = 8 - 1 = 7 = "111" in binary. TutorialsPoint - Complement of Base 10 Integer | One-Pass Bit Manipulation
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