I was searching about isolating the Right-most bit stuff in binary :
And I got this solution :
y = x & (-x)
so :
10111100 (x)
& 01000100 (-x)
--------
00000100
But now , I want to find the magnitude of a number by finding the left most digit ( not the sign though…)
How can I elaborate the solution of mine to find the most left-bit ?
examples :
10111100
01000100
There’s no similar O(1) bitwise trick to find the magnitude of a number. Many microprocessor instruction sets include a special instruction to “count leading zeroes.” There is no such operator in the C language family which gave JavaScript its bitwise functionality.
The only O(1) alternative is to use
Math.floor( Math.log( n ) / Math.LN2 )A quick trial ofgives
i == 31as the result, due to the<<operator using 32-bit two’s complement signed arithmetic.If you want to be a purist, you can repeatedly right-shift by one, which is O( log
n), or you can repeatedly right-shift by16 >> i, forifrom 0 to 4, rejecting shifts when the result is zero and otherwise accumulating16 >> i. That is O(log log N) where N is the maximum possible value forn, which means constant time, but in all probability slower thanMath.log.Code for the O( log log N ) algo:
Of course, for any of these, you have to left-shift one by the result to obtain the “leftmost 1-bit” rather than an index.
EDIT: Note, the
logbased implementation returns-Infinityfor zero, whereas themagfunction returns0, which is the same as its result for1. If you want to account for the possibility of no leftmost 1-bit existing, better to make it a special case.