Search⌘ K
AI Features

Solution: Complement of Base 10 Integer

Understand how to calculate the complement of a base 10 integer by manipulating its binary representation. Learn to apply bitwise XOR with a custom bitmask to flip bits efficiently. This lesson guides you through creating the bitmask, performing the XOR operation, and converting back to base 10, optimizing time and space complexity.

Statement

For any nn number in base 10, return the complement of its binary representation as an integer in base 10.

Constraints

  • 0n1090 \leq n \leq 10^9

Solution

So far, you’ve probably brainstormed some approaches and have an idea of how to solve this problem. Let’s explore some of these approaches and figure out which one to follow based on considerations such as time complexity and any implementation constraints.

Naive approach

To calculate the complement of any integer, we need to perform the following steps:

  1. Convert the integer to its binary value.

  2. Once we have the binary value, we can use a loop to incrementally convert each 11 to 00 and each 00 to 11.

  3. Now that we have the complemented binary number, we can convert it to its ...