Number Complement in C | Interview Question

Number Complement in C – Interview Question

Question

A complement of a number is defined as the bit-wise inversion: starting from the highest-order 1-bit, change every 1 to 0 and every 0 to 1. For example, if N = 5, N is represented as 101 in binary. The binary complement of N is 010, which is 2 in decimal notation.
Complete the function getIntegerComplement().

This function accepts N as parameter. The function should return the complement of N.The section of the program which parses the input and displays the output is already provided. Your task is to complete the body of the function provided so that it returns the correct output.

Constraints : 0 ≤ N ≤ 100,000.

Sample #1: 50
Output #1: 13

Explanation #1:
50 in decimal form equals 110010 when converted to binary.
Inverting the bit sequence gives 001101. This is the binary equivalent of decimal 13.

Input #2: 100
Output #02: 27

Explanation:
The binary representation of decimal 100 is 1100100. Inverting the sequence gives 0011011 which is the binary equivalent of decimal 27.

Solution in C

#include <stdio.h>


int find_highest_order(int num)
{
    int ret = 0;
    
    if(!num)
        return ret;
    
    while(num) {
        num >>= 1;
        ret++;
    }
        
    return ret;
}


int getIntegerComplement(int num)
{
    int order, i, result = 0;
    
    order = find_highest_order(num);
    
    if(!order) 
        return 0;
    
    for(i=0; i<order; i++) {
        num ^= (1 << i);
    }
    
    return num;
}

int main(void) {
    
    int res;
    int n;
    scanf("%d", &n);
    res = getIntegerComplement(n);
    printf("Complement is %d\n", res);
    return 0;
}

 

5 2 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
Ads Blocker Image Powered by Code Help Pro
Ad Blocker Detected!!!

It seems you are using adblocking software that prevents the page from fully loading.

The revenue we earn by advertisements is used to manage this website. Still, If you want to disable the ads, please become a premium member. Ads are disabled for Premium members.

Or please add www.embetronicx.com to your ad blocker whitelist or disable your adblocking software and reload the page.

Note: Please disable the ad blocker to access the membership pages also.

False Detection? Please write a mail to [email protected]

 
Refresh