> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Number Complement Python Solution with Tests

> Tested Python solution for LeetCode 476 with 22 pytest cases. Generate a practice environment with lcpy.

LeetCode 476, [Easy](/catalog/easy). Topics: [Bit Manipulation](/catalog/topics/bit-manipulation). [View on LeetCode](https://leetcode.com/problems/number-complement/description/).

Generate this problem as a practice environment: tested reference solution, 22 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 476   # by problem number
lcpy gen -s number_complement   # by problem name
```

## Problem

The \<strong>complement\</strong> of an integer is the integer you get when you flip all the \<code>0\</code>'s to \<code>1\</code>'s and all the \<code>1\</code>'s to \<code>0\</code>'s in its binary representation.

\<ul>
\<li>For example, The integer \<code>5\</code> is \<code>"101"\</code> in binary and its \<strong>complement\</strong> is \<code>"010"\</code> which is the integer \<code>2\</code>.\</li>
\</ul>

\<p>Given an integer \<code>num\</code>, return \<em>its complement\</em>.\</p>

### Examples

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

```
Input: num = 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
```

### Constraints

* `1 <= num < 2^31`

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/number_complement/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/number_complement/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(log num)
    # Space: O(1)
    def find_complement(self, num: int) -> int:
        mask = (1 << num.bit_length()) - 1
        return num ^ mask
```

## Complexity

| Time | Space |
| - | - |
| O(log num) | O(1) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.