Number Complement — LeetCode 476 Python Solution

EasyBit Manipulation
Problem
#476
Reading time
2 min

The 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.

Example

Input
num = 5
Output
2
Explanation
The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.

Python solution

Python
class Solution:
    def findComplement(self, num: int) -> int:
        return num ^ ((1 << num.bit_length()) - 1)

Complexity

MeasureComplexity
TimeO(\log \textit{num}), where \textit{num} is the input integer
SpaceO(1) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 476. Number Complement is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 476. Number Complement?
LeetCode 476. Number Complement is rated Easy on LeetCode.
What is the time complexity of LeetCode 476. Number Complement?
The Python solution on this page runs in O(\log \textit{num}), where \textit{num} is the input integer.
What is the space complexity of LeetCode 476. Number Complement?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 476. Number Complement cover?
LeetCode 476. Number Complement is tagged Bit Manipulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview