Microsoft Interview Question
Software Engineer / DevelopersCountry: -
I think this should work... it is obvious that the solution for -ve no's is hardware dependent i.e. for 32 bit systems it is different then for same -ve no. on 64 bit system...
#include<stdio.h>
int main()
{
int a,b,in_a,in_b;
printf("\n Enter a : ");
scanf("%d",&a);
printf("\n Enter b : ");
scanf("%d",&b);
in_a=find(a);
in_b=find(b);
printf("\n No. of 1's in 2's compliment of a : %d",in_a);
printf("\n No. of 1's in 2's compliment of b : %d\n\n",in_b);
return 0;
}
int find(int a)
{
int ret=0;
if(a>0)
{
while(a)
{
if(a&1)
ret++;
a=a>>1;
}
}
else if(a==0)
ret=0;
else
{
a=~a;
ret=32; //here ret is maximum bits in the representation of number and it varies from machine to machine
while(a>0)
{
if(a&1)
ret--;
a=a>>1;
}
}
return ret;
}
sample input :
a=2
b=-7
output :
no.of 1's in 2's compliment of a : 1
no. of 1's in 2's compliment of b : 30
Get the 2's complement of the number by doing ~n +1
- adroitninja October 22, 2011Then count the number of 1s using x&(x-1)