Complement of Base 10 Integer Problem
Description
LeetCode Problem 1009.
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
5is"101"in binary and its complement is"010"which is the integer2.
Given an integer n, return its complement.
Example 1:
Input: n = 5
Output: 2
Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
Example 2:
Input: n = 7
Output: 0
Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.
Example 3:
Input: n = 10
Output: 5
Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
Constraints:
0 <= n < 10^9
Note: This question is the same as 476: https://leetcode.com/problems/number-complement/
Solution
Approach: XOR with a Mask
Flipping bits is XOR with 1. We want to flip exactly the bits of n's binary form, and not the leading zeros above it, so we XOR with a mask of 1s that is as long as n.
Find the smallest power of two mask that is greater than n by doubling from 1. Then mask - 1 is all 1s over exactly the bits of n (for n = 10 = 1010, mask = 10000 and mask - 1 = 1111), and the answer is n ^ (mask - 1) (1010 ^ 1111 = 0101 = 5).
The one tricky case is n = 0: its binary form is "0", one bit, and the complement is 1. The loop would give an empty mask, so we return 1 directly.
Since n < 10^9 < 2^30, the mask stays at most 2^30 and fits in a 32-bit integer.
Complexity: O(log n) time and O(1) extra space.
class Solution:
def bitwiseComplement(self, n: int) -> int:
if n == 0:
return 1 # "0" has one bit, and it flips to 1
mask = 1
while mask <= n:
mask <<= 1
# mask - 1 is all 1s over exactly the bits of n, so XOR flips just those.
return n ^ (mask - 1)