c++ - How get smallest n, that 2 ^ n >= x for given integer x in O(1)? -
how given unsigned integer x
find smallest n, 2 ^ n
≥ x
in o(1)? in other words want find index of higher set bit in binary format of x
(plus 1 if x
not power of 2) in o(1) (not depended on size of integer , size of byte).
if have no memory constraints, can use lookup table (one entry each possible value of x
) achieve o(1) time.
if want practical solution, processors have kind of "find highest bit set" opcode. on x86, instance, it's bsr
. compilers have mechanism write raw assembler.
Comments
Post a Comment