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
Number Complement INPUT Decimal num = 5 Binary Representation 1 0 1 2^2=4 2^1=2 2^0=1 5 = 4 + 0 + 1 "101" in binary Input Value num = 5 ALGORITHM STEPS 1 Get Binary Length Find bits needed: 3 bits 2 Create Bit Mask mask = (1 << 3) - 1 = 7 3 XOR Operation num XOR mask = result 4 Return Complement 5 XOR 7 = 2 XOR Truth Table 5: 1 0 1 7: 1 1 1 XOR: 0 1 0 Result = 2 FINAL RESULT Complement Binary 0 1 0 Bit Flip Comparison Original: 1 0 1 Flipped: 0 1 0 Each bit inverted Decimal Value 0 + 2 + 0 = 2 Output Value 2 OK Key Insight: The complement is found using XOR with a mask of all 1s. For a number with n bits, the mask is (2^n - 1). XOR flips each bit: 1 XOR 1 = 0, 0 XOR 1 = 1. Time: O(log n), Space: O(1) TutorialsPoint - Number Complement | Optimal Solution (Bit Manipulation)
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
23.4K Views
Medium Frequency
~15 min Avg. Time
987 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