Interview Questions

Microsoft Interview Question for Software Engineer / Developers

Microsoft Interview Questions and Answers


(Continued from previous question...)

Microsoft Interview Question for Software Engineer / Developers

Question:
Two numbers A and B are given. Both can be -ve or +ve. find no of 1's in 2's compliment representation between A and B.


maybe an answer:
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

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

(Continued on next question...)

Other Interview Questions