Interview Question
Software Engineer / Developers#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <assert.h>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[])
{
int i = 0;
cin>>i;
int index = 0, temp = i;
if(temp&0xffff0000)
{
index += 16;
temp = (temp&0xffff0000)>>16;
}
if(temp&0x0000ff00)
{
index += 8;
temp = (temp&0x0000ff00)>>8;
}
if(temp&0x000000f0)
{
index += 4;
temp = (temp&0x000000f0)>>4;
}
if(temp&0x0000000c0)
{
index += 2;
temp = (temp&0x0000000c0)>>2;
}
if(temp&0x00000002)
++index;
cout<<index<<endl;
return 0;
}
//geniusxsy's post actually said all, I just want to check if I can finish it in 15mins
a question for you:
how do you make your code machine independent? i.e., it should work for various size of int.
no, I mean, how would you do to make your code more generic to handle int of 32bit/64bit even 128bit...
int most_significatn_bit(const unsigned int input)
{
if (input == 0) {
return 0;
}
unsigned int n = 0x80000000;
int nIndx = 32;
for(int i = 32; i > 0; i --) {
if (input & n) {
return i;
}
n = n >> 1;
}
return 0;
}
int most_sign_One(int input)
{
int tmp = 1;
int i = 0;
while(input >= tmp)
{
i++;
tmp = tmp<<1;
}
return i-1;
}
Depending upon the architecture of the machine, the most significant bit is either the left most or the right most. So one way could be to left shift or right shift by 1
// find the position of the most significant 1 bit?
int GetFirstMsb1(int num)
{
if (!num)
return -1;
int pos = 0, i = 0;
unsigned int mask = 0xff000000;
int n = num & mask;
do
{
if (n)
{
if (n >= 128)
pos = 0 + i;
else if (n >= 64)
pos = 1 + i;
else if (n >= 32)
pos = 2 + i;
else if (n >= 16)
pos = 3 + i;
else if (n >= 8)
pos = 4 + i;
else if (n >= 4)
pos = 5 + i;
else if (n >= 2)
pos = 6 + i;
else if (n >= 1)
pos = 7 + i;
return pos;
}
mask >>= 8;
n = num & mask;
i += 8;
}
while (i < sizeof(int) * 8);
return pos;
}
i is the number of input
- geniusxsy January 26, 2010int count=0;
if(i&0xffff0000){ count |= 1<<4; i = (i&0xffff0000)>>4;}
...