Number Complement

The complement of an integer is the integer you get by flipping every 0 to 1 and every 1 to 0 in its binary representation, without leading zeros. For example, 5 is "101" in binary and its complement is "010", which is 2. Given a positive integer num, return its complement.

30:00

Number Complement
easy
Free written solution
Topics
Companies

The complement of an integer is the integer you get by flipping every 0 to 1 and every 1 to 0 in its binary representation, without leading zeros. For example, 5 is "101" in binary and its complement is "010", which is 2. Given a positive integer num, return its complement.

Example 1:
Input: {"num":5}
Output: 2
Constraints:
  • 1≤num<2311 \leq \text{num} < 2^{31}

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"num":5}

num = 5 is 101 in binary (3 bits). Flipping must stop at its highest 1: the leading zeros are not part of the number.

Flip only the bits num actually uses

3 significant bits

num
0
0
0
1
0
1
mask
·
·
·
·
·
·
num^mask
·
·
·
·
·
·
5
4
3
2
1
0

dashed = leading zeros (left alone)

mask 1 = flip this bit

num = 5

mask = -

Variables
VariableValue
num5
DepthFunction Call
Stack empty
0/6