How to solve complement of base 10 integer question on coding platforms.

Table of contents

Hello everyone, in this article I will tell you how you can solve the complement of base 10 integer question on coding platforms. So in this article, I am using C++ language but I will focus on the concept of solving question , so that you can solve the question in any language. So let's start.

I am not writing the whole syntax as if you are here to read this article, I am assuming that you already know the syntax, and how to write a C++ program. I am just writing a function that will return the complement of a number.

Approach

int bitwiseComplement(int n) {

int m = n;

int mask = 0;

if(n==0)

{

return 1;

}

while(m!=0) {

mask = (mask<<1)|1;

m = m>>1;

}

int ans = (~n) & mask;

return ans;

}

So In the above approach, we have to make a mask that will be equal to 1 for all the bits of the n. For ex - if no is 5 then the number of bits will be 3, so we need 3 ones in the mask and that will be 111. And to make that mask, first, we have to take it as zero, then we will do a left shift and then will do an OR operation with 1 until the number not becomes zero. As we get a mask, as we want then we will do AND operation between the mask and (~n). When we will do this we will get our answer.

I hope that you like our blog, if there are any queries or questions, you can post them in the comment section. Thank you