Complement of Base 10 Integer — LeetCode 1009 Python Solution

EasyBit Manipulation
Problem
#1009
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
n = 5
Output
2
Explanation
5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.

Python solution

Python
class Solution:
    def bitwiseComplement(self, n: int) -> int:
        if n == 0:
            return 1
        ans = i = 0
        while n:
            ans |= ((n & 1 ^ 1) << i)
            i += 1
            n >>= 1
        return ans

Complexity

MeasureComplexity
TimeO(\log n), where n is the given decimal number
SpaceO(1) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1009. Complement of Base 10 Integer 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 1009. Complement of Base 10 Integer?
LeetCode 1009. Complement of Base 10 Integer is rated Easy on LeetCode.
What is the time complexity of LeetCode 1009. Complement of Base 10 Integer?
The Python solution on this page runs in O(\log n), where n is the given decimal number.
What is the space complexity of LeetCode 1009. Complement of Base 10 Integer?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1009. Complement of Base 10 Integer cover?
LeetCode 1009. Complement of Base 10 Integer 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