Ticker

6/recent/ticker-posts

leetcode-476 Number complement



 in the problem there given a positive integer num you need to convert in decimal to binary(0,1) let take num= 5 the binay convertion is 5(101) according to 8421 code we need complement of num is 010 and the integer  2 return its complement 

Input:5

Output:2

Explanation: the binary representation of 5 is 101 (no leading zero bits), and its compliment is 010. So you need to output 2

Input : 18

Output: 13

Explanation: The binary representation of 18 is 10010 (no leading zero bits), and its complement is 01101. so you need to output 13

The logic is:

without using complement the 5 binary code is 101 so we need convert to binary to decimal how to get 5, so like this the complement of 5 is also understand here there is any zero in binary code the 2 pow of any value is zero.


with complement of 5 is 2(010) so that is only main point to solve when ever there is zero only we do operation when there is one we no need for operation of 1 

When you understand the logic of the binary conversion of decimal to binary to improve your logical thinking by solve this problem click here to understand the logic of binary convertion 

This is the code in C++:

class Solution {
public:
    int findComplement(int num) {
        int sum=0;
        int i=0;
        while(num>0){
            if(num%2==0){
                sum+=pow(2,i)*1;
                }
            i++;
            num=num/2;
            }
        return sum;
    }
};

Explanation of the code:

we need sum of all converting values so int sum=0; it is we declared in while loop we converting num to binary  and also do operation where num%2 get the last value of the binary reperation so we need to 101 and by num=num/2to remove last value 10 and again the same proceess until the while loop break/false 1as i said what we neccessary that only we do if(num%2==0) this condition only sum and i++ is not conatant it increases until the condition of while false there is more important thing is i is started with zero that why  we declered int i=0; and the pow(2,i) is where the i=0 the binary of 5(101) the one is not equal to 0 so the condtion false no operation done and it reduced  num=num/2; so 10 and i increases to i=1 here binary(10) so there is condtion was true operation done (2^1)*1=>2 that added to sum and the binary reduced (1) then again the condition was false so again it reduced to 0 and while condition false the sum was returned 

Also Read

Post a Comment

0 Comments