Number Complement - Problem
Binary Number Complement Challenge

In the world of binary operations, every number has an alter ego - its complement! Your mission is to find this binary opposite.

Given an integer num, you need to flip every bit in its binary representation:
โ€ข Convert all 0s to 1s
โ€ข Convert all 1s to 0s

Example: The number 5 in binary is 101. Flipping the bits gives us 010, which equals 2 in decimal.

Note: We only consider the significant bits (ignore leading zeros in the original number).

Input & Output

example_1.py โ€” Basic Case
$ Input: num = 5
โ€บ Output: 2
๐Ÿ’ก Note: The binary representation of 5 is 101 (in binary). The complement flips all bits: 101 โ†’ 010, which equals 2 in decimal.
example_2.py โ€” Single Bit
$ Input: num = 1
โ€บ Output: 0
๐Ÿ’ก Note: The binary representation of 1 is 1 (in binary). The complement flips the single bit: 1 โ†’ 0, which equals 0 in decimal.
example_3.py โ€” Larger Number
$ Input: num = 7
โ€บ Output: 0
๐Ÿ’ก Note: The binary representation of 7 is 111 (in binary). The complement flips all bits: 111 โ†’ 000, which equals 0 in decimal.

Constraints

  • 1 โ‰ค num โ‰ค 231 - 1
  • The input is guaranteed to be a positive integer
  • Only consider the significant bits (no leading zeros)

Visualization

Tap to expand
Number Complement VisualizationOriginal Number: 5101โ‚‚XOR Mask: 7111โ‚‚โŠ• XORResult: 2010โ‚‚
Understanding the Visualization
1
Identify Bit Pattern
Look at the binary representation of the input number
2
Create Universal Flipper
Make a mask with all 1s that covers exactly the same bit positions
3
Flip All Switches
XOR the number with the mask to flip every bit simultaneously
Key Takeaway
๐ŸŽฏ Key Insight: XOR with a mask of all 1s efficiently flips every bit in the significant portion of the number
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
78.0K Views
Medium Frequency
~8 min Avg. Time
2.4K 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