How to calculate complement number in java

NUMBER COMPLEMENTA complement of a number defined as bitwise inversion starting from highest order 1-bit change every 1 to 0 and every 0 to 1.for example n=5(decimal) = 101(binary) so the binary complement is =010(binary) = 2(decimal)
Constaints : n<=0<=100000
input : 50(110010)
output : 13(001101)
SOURCE : NumberComplement.java

static int getIntegerComplement(int n)
{
int comp = 0;
int rem=0;
int count =0;

if (n == 1)
{
return 0;
}
else if(n == 0)
{
return 1;
}
while(n>1)
{
rem = n % 2;
n= n / 2;
if(rem==0)
comp= (int) (comp+1*Math.pow(2, count));
count++;
}
if(n == 0)
{
comp= (int) (comp+1*Math.pow(2, count));
}


return comp;
}








Sandeep Kumar D

Hi, I have written and developed this post so that most of people will be benefited. I'm committed to provide easy and in-depth tutorials on various technologies.I hope it will help you a lot.

- Sandeep Kumar D

Follow Me @Google+




SHARE

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment