/*
* Given a 64-bit signed long, find the position of the most significant set bit (a "set bit" means a bit whose value is 1). The least significant bit is considered to have position 0, the next least significant bit has position 1, and so on.
* If there are no set bits at all, print -1.
* Example Inputs:
* 0
* -1
* 25
* Outputs (respectively):
* -1
* 63
* 4
* Solution Guidance:
* Let k be the bit width (maximum number of bits) of the primitive.
* Easy: O(k) time.
* Moderate: O(log(k)) time.
*/
#include <iostream>
using namespace std;
inline bool isSet(long long int n,int i)
{
long long int x = 1;
x <<=i;
if(x&n)
return true;
return false;
}
//EASY
int getSetMSBPositionEASY(long long int n)
{
int size = sizeof(n);
size <<=3;
for(int i=size-1; i>=0; i--)
{
if(isSet(n,i))
return i;
}
return -1;
}
//MODERATE
int getSetMSBPositionMODERATE(long long int n)
{
int size = sizeof(n);
size <<=3;
int start = size-1;
int end = 0;
int mid = (start+end)/2;
while( start >= end)
{
long long int check = ~(0LL)^((1LL<<mid)-1);
if(n & check)
{
end = mid+1;
}
else
{
start = mid-1;
}
mid= (start+end)/2;
}
return mid;
}
int main()
{
long long int n;
int testCases;
//FIRST ENTER NUMBER OF TEST CASES
cin>>testCases;
for(int i=0; i<testCases; i++)
{
cin>>n;
if(!n)
cout<<-1;
else
{
cout<<"\nEASY = "<<getSetMSBPositionEASY(n);
cout<<"\nMODERATE = "<<getSetMSBPositionMODERATE(n);
}
}
}
Monday, 2 September 2013
HIT BIT
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment