Find One’s Complement of an Integer in C++

C++Server Side ProgrammingProgramming

In this section, we will see how to find the 1’s complete of an integer. We can use the complement operator to do this task very fast, but it will make 32bit complemented value (4-bype integer). Here we want complement of n bit numbers.

Suppose we have a number say 22. The binary equivalent is 10110. The complemented value is 01001 which is same as 9. Now the question comes, how to find this value? At first we have to find number of bits of the given number. Suppose the count is c (here c = 5 for 22). We have to make 5 1s. So this will be 11111. To make this, we will shift 1 to the left c number of times, then subtract 1 from it. After shifting 1 to the left 5 times, it will be 100000, then subtract 1, so it will be 11111. After that perform XOR operation with the 11111 and 10110 to get the complement.

Example

 Live Demo

#include <iostream>
#include <cmath>
using namespace std;
int findComplement(int n) {
   int bit_count = floor(log2(n))+1;
   int ones = ((1 << bit_count) - 1);
   return ones ^ n;
}
int main() {
   int number = 22;
   cout << "One's Complement of " << number << " is: " << findComplement(number);
}

Output

One's Complement of 22 is: 9
raja
Published on 25-Sep-2019 13:16:39
Advertisements