Number Complement - Complete Solution Guide
Number Complement is LeetCode problem 476, 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 num , return its complement . Example 1: 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. Example 2: Input: num = 1 Output: 0 Explanation:
Detailed Explanation
The problem asks us to find the complement of a given integer. The complement is obtained by flipping all the bits (0s to 1s and 1s to 0s) in the binary representation of the number. For instance, the binary representation of 5 is '101', so its complement is '010', which is equal to 2 in decimal. The input is a positive integer 'num', and the output should be its complement.
Solution Approach
The solution involves first determining the number of bits required to represent the input number in binary. Then, we create a mask with the same number of bits, all set to 1. Finally, we perform a bitwise XOR operation between the original number and the mask. The result of the XOR operation is the complement of the original number.
Step-by-Step Algorithm
- Step 1: Calculate the number of bits required to represent the number `num` in binary. In Python, we can use `num.bit_length()`. In Java, `Integer.highestOneBit(num)` gives the highest set bit, shifting it left by one and subtracting one creates the desired mask.
- Step 2: Create a mask by left-shifting 1 by the number of bits calculated in Step 1, and then subtracting 1. This results in a number with all the bits set to 1 for the required length. (e.g., if `bits` is 3, the mask will be `(1 << 3) - 1 = 8 - 1 = 7`, which is `111` in binary).
- Step 3: Perform a bitwise XOR operation (^) between the original number `num` and the `mask`. This flips all the bits in `num` that correspond to the bits set to 1 in the `mask`. The result of this XOR operation is the complement.
- Step 4: Return the result of the XOR operation.
Key Insights
- Insight 1: The core idea is to create a 'mask' that has the same number of bits as the input number 'num', with all bits set to 1.
- Insight 2: By XORing the number 'num' with the 'mask', we effectively flip all the bits, thus computing the complement.
- Insight 3: Determining the correct number of bits for the mask is crucial. Leading zeros in the original number are irrelevant for the complement calculation.
Complexity Analysis
Time Complexity: O(1)
Space Complexity: O(1)
Topics
This problem involves: Bit Manipulation.
Companies
Asked at: Cloudera.