Number Complement — LeetCode 476 Python Solution
- Problem
- #476
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
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
class Solution:
def findComplement(self, num: int) -> int:
return num ^ ((1 << num.bit_length()) - 1)Complexity
| Measure | Complexity |
|---|---|
| Time | O(\log \textit{num}), where \textit{num} is the input integer |
| Space | O(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.