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;
}

 

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
Table of Contents