Infosys Interview Question
Software Engineer / DevelopersThe first part to your answer is correct... The XOR bit... However when finding the number of set bits in diffnum. You will have to right shift the num. And why did you declare count be unsigned??? It can be a signed int.
The answer below only works if A ^ B >= 0.
{{
int BitSwapReqd(int A, int B)
{
int count = 0;
int xornum = A ^ B;
while(xornum)
{
//finding if LSB is set. If so increment count
if(xornum & (xornum-1))
count++;
//Right shift to get rid of a bit.
xornum = xornum >> 1;
}
return count;
}
Even in the above algo, the part to calculate xornum is corrent and the remaining task is to calculate total no. of set bits in xornum which can be done by checking xornum AND '1' as mentioned in above comment and then right shift the num by 1.
both are right. note in the first solution, diffnum &= diffnum-1;, which sets diffnum = diffnum & (diffnum-1), making the rightmost bit to 0; in the second solution, instead of "if (xornum & (xornum-1))", if you did "xornum= xornum & (xornum-1)", you would not need the right shift to get rid of the bit.
Here is the code..
#include<stdio.h>
void main()
{
int a,b,c,count=0;
printf("Enter the two numbers \n");
scanf("%d", &a);
scanf("%d", &b);
c = a^b;
//Counting the no. of ON bits in c
while(c)
{
count++;
c = c & (c-1);
}
printf("The total no. of transformations required is %d\n",count);
}
public class BinaryAnd {
public static void main(String [] args){
int a=10;
int b=7;
//System.out.println(Integer.toBinaryString(a));
//System.out.println(Integer.toBinaryString(b));
int c=a^b;
String s1=Integer.toBinaryString(c);
System.out.println(s1);
int count=0;
for(int i=0;i<s1.length();i++){
if(s1.charAt(i)=='1')count++;
}
System.out.println("The number of bit swaps required are: "+count);
//System.out.println(c);
}
}
int BitSwapReqd(int A, int B)
- brijesh kumar jaiswal April 11, 2007{
unsigned int count;
int diffnum = A ^ B;
for(count=0; diffnum; count++){
diffnum &= diffnum-1;
}
// here count is total no. of bit
}