Texas Instruments Interview Question
Software Engineer / DevelopersAnswer is incomplete. This will not return the position. The bit needs to be shifted in order to count the position.
little optimized
int bitset(unsigned long num)
{
int count = 0;
while(num) {
switch (num & 0xf) {
case 1:
case 3:
case 5:
case 7:
return count + 1;
case 2:
return count + 2;
case 4:
return count + 3;
case 8:
return count + 4;
default:
break;
}
num >>= 4;
count += 4;
}
}
the case 8: never happens, this was code snippet I copied from much more optimized code.
#include <stdio.h>
int bitset(int n)
{
int i=1,pos=1;
for(;i<sizeof(int)*8;i*=2,pos++)
{
if((n&i)==i)
return pos;
}
return -1;
}
int main()
{
int n,pos;
printf("Enter no. to find its first set bit position from the right side: ");
scanf("%d",&n);
pos=bitset(n);
if(pos==-1)
printf("\nNo. is zero");
else
printf("\nFirst set bit position from the right side: %d",pos);
}
for(count=0;count<31;count++) // 31 if it is a 32 bit integer
- Anonymous August 02, 2010{
if((N>>count)&1==1)
{
print(the position is count)
break;
}
}