Advertisement

Complement of Base 10 Integer - LeetCode 1009 Solution

Complement of Base 10 Integer - Complete Solution Guide

Complement of Base 10 Integer is LeetCode problem 1009, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

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

Detailed Explanation

This problem asks us to find the "complement" of a given base 10 integer `n`. The key here is understanding what "complement" means in this specific context. It's not the mathematical complement or the two's complement used for negative numbers. Instead, we are instructed to take the binary representation of `n` and flip all its `0`s to `1`s and `1`s to `0`s. The crucial detail, subtly conveyed by the example, is that we only flip the *significant* bits. For instance, `n = 5` is `"101"` in binary. Its complement is `"010"`, which translates back to `2` in base 10. If we were to consider a fixed-width 32-bit representation (e.g., `00...0101`), flipping all bits would yield `11...1010`, which is a large negative number, not `2`. This distinction between fixed-width bitwise NOT and flipping *only* the relevant bits is where the problem gets interesting. The challenge, therefore, is to determine the precise length of the binary string we need to consider. We can't just use a language's built-in bitwise NOT operator (`~`) because that typically operates on the underlying fixed-size integer type and would flip leading zeros as well. For example, in Python, `~5` yields `-6`, which is not `2`. We need a method to confine the bit-flipping operation to just the bits that constitute the number itself, ignoring any leading zeros that are merely artifacts of the integer's storage size. The problem statement also presents a simple edge case: what is the complement of `0`? Its binary is `0`, so its complement would be `1`.

Solution Approach

The provided solution elegantly solves this by first identifying the number of bits required to represent `n`, and then constructing a 'mask' of all ones with that exact length. Let's trace it: first, it explicitly handles the `n=0` case, returning `1`. For any `n > 0`, it determines `num_bits`, which is the count of significant bits in `n`'s binary representation. This is achieved by repeatedly right-shifting `n` (`temp >>= 1`) until it becomes zero, incrementing `num_bits` each time. For `n=5` (binary `101`), `num_bits` would become `3`. Once `num_bits` is known, a mask is created using `mask = (1 << num_bits) - 1`. This is a powerful bit manipulation trick: `1 << num_bits` gives a `1` followed by `num_bits` zeros (e.g., `1 << 3` is `1000` binary, or `8` decimal). Subtracting `1` from this yields a number consisting of `num_bits` ones (e.g., `1000 - 1 = 111` binary, or `7` decimal). Finally, `n` is XORed (`^`) with this mask. The XOR operation has the property that `X ^ 1 = ~X` (flips the bit) and `X ^ 0 = X` (leaves the bit unchanged). Since our mask consists solely of ones in the positions corresponding to `n`'s significant bits, XORing `n` with this mask effectively flips exactly those bits, producing the desired complement. Any bits beyond `num_bits` are implicitly `0` in `n` and `0` in our mask (assuming sufficient integer width for `mask`), so `0 ^ 0 = 0`, preserving the effect of only flipping relevant bits.

Step-by-Step Algorithm

  1. **Step 1: Handle the base case:** If the input `n` is 0, return 1.
  2. **Step 2: Determine the number of bits:** Find the number of bits required to represent `n` in binary. This can be done efficiently using a loop (as shown) or using `log2(n) + 1` (logarithm method).
  3. **Step 3: Create a bitmask:** Generate a mask with all bits set to 1, having the same number of bits as `n`. This is done by left-shifting 1 by the number of bits and subtracting 1. This creates a number where all bits are 1s (e.g., if `num_bits` is 3, the mask will be 111 in binary, which is 7 in decimal).
  4. **Step 4: Calculate the complement:** Perform a bitwise XOR operation between the input `n` and the created mask. The XOR operation will flip each bit, thus generating the complement.

Key Insights

  • The core problem lies in *selectively* flipping bits. We are not performing a standard bitwise NOT (`~`) operation that would flip all bits in an integer's fixed-size storage (e.g., 32-bit), but rather only the bits that constitute the number itself in its minimal positive binary form.
  • The solution cleverly generates a 'mask' of all ones that has the exact same number of bits as the input number `n`. This mask is then used with the XOR operator to flip precisely those bits without affecting any leading (insignificant) zeros.
  • An efficient way to construct a mask of `k` ones is `(1 << k) - 1`. This technique is valuable in bit manipulation problems for creating specific bit patterns quickly. The `while` loop simultaneously identifies `k` (the number of significant bits) and prepares for this mask generation.

Complexity Analysis

Time Complexity: O(log n)

Space Complexity: O(1)

Topics

This problem involves: Bit Manipulation.

Companies

Asked at: Cloudera, Snap.