Complement of Base 10 Integer

The complement of an integer is what you get by turning every 0 into a 1 and every 1 into a 0 in its binary form, with no leading zeros. For example, 5 is "101" in binary, so its complement is "010", which is 2. Given an integer n, return its complement.

30:00

Complement of Base 10 Integer
easy
Free written solution
Topics
Companies

The complement of an integer is what you get by turning every 0 into a 1 and every 1 into a 0 in its binary form, with no leading zeros. For example, 5 is "101" in binary, so its complement is "010", which is 2. Given an integer n, return its complement.

Example 1:
Input: {"n":5}
Output: 2
Constraints:
  • 0≤n<1090 \leq n < 10^9

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

Run code to see results.

Input
arr ={"n":5}

n = 5 is 101 in binary. Read its bits from the bottom, write each one flipped into result, and stop when n runs out of bits.

Read at bit 0, write flipped at bit 0

3 bits in n

input
1
0
1
n
1
0
1
result
·
·
·
3
2
1
0

yellow box = read head (n) / write head (result)

dashed = past the highest 1, never written

n = 5

bit = 0

result = 0

shifted out of n:

nothing yet

Variables
VariableValue
n5
DepthFunction Call
Stack empty
0/12