Mxl Mxl-Fr-402 Table Interview Boundary Microphone For Field Recording (Google Affiliate Ad)Your writing a normal client server program and there is a problem, the data length you are expecting is a power of 2. So now how can we check if it is a power of 2 ? how how how? i thought thought and thunk :P and there were no answers, so at that time what one should do? ask everyone you know and find best answer and this one is the best i guess !!.
So here is the solution :
Let n be the number which you want to test .... wait wait wait .... just now i asked my roomie abt this problem and he gave me one more solution that too on the fly. I think it should work, we just checked it with numbers up to 1024 so it seems the logic is good !! but i don't know how efficient it will be if one wants to implement it.
Solution given by my roomie goes like this.
Convert the given number to binary and if it has just one bit as 1 tada !! its a power of 2 !! so i think one can implement it this way
// handle the special case where n = 1.
while(n!=0)
{
int i = n % 2;
n = n/2;
if(n == 1)
{
count++;
}
if(i == 1)
count++;
if(count>1)
{
notPowerOf2 = TRUE;
Break;
}
}
but the time complexity is O(n) for this .
Now i ll go for the actual solution which i came to know by someone.The BEST logic i have ever come across !! just a single line of code to decide whether its a power of 2 or not !! so here it goes
if((n & n-1) == 0)
// Its a power of 2
And time complexity its just O(1) .. What say !!
Please do let me know if there are any problems with this logic and do suggest me if there are any other good solution.
So here is the solution :
Let n be the number which you want to test .... wait wait wait .... just now i asked my roomie abt this problem and he gave me one more solution that too on the fly. I think it should work, we just checked it with numbers up to 1024 so it seems the logic is good !! but i don't know how efficient it will be if one wants to implement it.
Solution given by my roomie goes like this.
Convert the given number to binary and if it has just one bit as 1 tada !! its a power of 2 !! so i think one can implement it this way
// handle the special case where n = 1.
while(n!=0)
{
int i = n % 2;
n = n/2;
if(n == 1)
{
count++;
}
if(i == 1)
count++;
if(count>1)
{
notPowerOf2 = TRUE;
Break;
}
}
but the time complexity is O(n) for this .
Now i ll go for the actual solution which i came to know by someone.The BEST logic i have ever come across !! just a single line of code to decide whether its a power of 2 or not !! so here it goes
if((n & n-1) == 0)
// Its a power of 2
And time complexity its just O(1) .. What say !!
Please do let me know if there are any problems with this logic and do suggest me if there are any other good solution.
Comments
Post a Comment