Write a pgm to complement an integer.

0 views
Skip to first unread message

Kumar Anurag

unread,
Jun 19, 2010, 9:13:35 AM6/19/10
to DiscoLinux
example.

ex1
input : 9 //(1001)
ouput 6 //(0110)


ex2:
input: 3
ouput 0

Note: consider that integer takes 16 bits(2 bytes) on your os

Kumar Anurag

unread,
Jun 20, 2010, 7:39:54 PM6/20/10
to DiscoLinux
This is one of many solutions, u can have ur own way to solve it.

#include<cmath>
#include<cstdio>
#include<iostream>
#include<cstdlib>
using namespace std;



void Complement(int N){

int a=pow(2,16)-1;

int ans1=N^a;

int n=N,len=0;
if(n==0) len=1;
while(n>0){

++len;

n/=2;

}

int a2=pow(2,len)-1;

int final=ans1&a2;

printf("%d\n",final);

}

int main()
{
cout<<"enter the number whose complement u want to
find(number>=0)"<<endl;
int num;
scanf("%d",&num);
cout<<"Answer is\n";
Complement(num);

return 0;

Pervez Alam

unread,
Jun 22, 2010, 1:37:56 AM6/22/10
to DiscoLinux
Hi, the best way is to find max no of BITs required to store that no,
suppose it is X

-Now Complement Lowest X bits
-Leave 16-X bits as it is.

Life is so Simple.
ok
BYE
Reply all
Reply to author
Forward
0 new messages