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

 

%d bloggers like this: