Complement of Base 10 Integer — LeetCode 1009 Python Solution
- Problem
- #1009
- 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
- n = 5
- Output
- 2
- Explanation
- 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
Python solution
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(\log n), where n is the given decimal number |
| Space | O(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.