Leetcode 1009 and 476 both question are same but there is slight changes in the constraint part...
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" 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.
Approach:
Base Case- If the enter number is 0, then its output should be 1, and vice versa.
Other Cases-
Suppose the input is 5.
binary of 5 in 32 bits: 00000000........101
We have to find the complement of this, which means 0 becomes 1 and 1 becomes 0.
To do this, first we will create a mask variable. The starting value of this variable is 0.
After that, the mask variable will be left shifted three times because the most significant 1 comes at the third place in the binary of 5, and/or an operation will happen to append 1 at the end of the mask variable.
So the mask variable looks like 000000000.....111.
Now for the output, we're going to do ~5 & mask
Code:
I hope you will understand the solution to this problem. If not, let me know in the comments.
Comments
Post a Comment
if you have any doubts let me know.