Simple solution with explanation using bit manipulation in C programming language


  • 0
    A
    /*
     * main.c
     *
     *  Created on: Sep 2, 2017
     *      Author: Prakhar Avasthi
     */
    
    /*
     * This problem requires knowledge of bit manipulation.
     * In this problem, we need to know each bit of the number
     * and best way to find that is to perform & operation on number with 1
     * and right shift the number in a loop to get all other bits.
     * So to find complement, if bit is 0 multiply that bit with it's bit value.
     * Add all bit values with 0 and you will get your result.
     * */
    
    #include<stdio.h>
    
    int findComplement(int num) {
    	int mul = 1, result = 0, bit = 0;
    
    	while(num > 0)
    	{
    		bit = num & 1;
    		if(bit==0)
    			result = result + mul;
    
    		mul = mul*2;
    		num = num>>1;
    	}
    	return result;
    }
    
    int main()
    {
    	int test_case, num;
    
    	setbuf(stdout, NULL);
    
    	scanf("%d", &test_case);
    
    	while(test_case--)
    	{
    		scanf("%d", &num);
    		printf("Compliment: %d \n", findComplement(num));
    	}
    
    	return 0;
    }
    
    
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.