Sunday, July 28, 2013

Find the position of the most significant set bit in a 64-bit signed long int.

HiBit:-
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.

Solution:-
Complexity O(k)
logic:- Check every bit from left to right, return the position of the last set bit
#include <iostream>
 
using namespace std;
int MaxBit(long long int n)
{ long long int val=1;
    int count=-1;
    if(n<0)
     return 63;
   
    while(n)
    {
     if((val&n))
     n=n^val;
     val<<=1;
     count++;
    }
return count;
}
 
int main()
{  long long int N=0;
   cout <<MaxBit(N) << endl; 
   
   return 0;
}

Note:- Complexity logK.
Logic:- Used Binary search to find the most significant bit.
#include <iostream>
 
using namespace std;
 
int MaxBit(long long int n)
{
 
if(n<0)return 63;
else if(n==0) return -1;
int count=32;
int temp=32;
long long int k=0;
long long int t=1;
while(n)
{
long long int val=~k<<count-1;
if((n&val)>(t<<count-1))
{    
    temp/=2;
    count+=temp;
}
else if((n&val)<(t<<count-1))
{  
    temp/=2;
    count-=temp;
 
}
else
 return count-1;
}
return -1;
}
int main()
{  long long int n;
   cin>>n;
   cout <<MaxBit(n)<< endl; 
   
   return 0;
}
//Happy coding 
If you do find bug feel free to comment....or if you do know better solution do not forget to acknowledge us. 

No comments:

Post a Comment