方法:因为是将n转化为2的n次幂,需要从二进制角度来看待问题。
例如:5 = 0101, 9 = 1001,
对于5来说要找到的是8 = 1000, 9来说要找到的是16 10000
8 = 7+1 = 0111 +1;
16 = 15+1 = 01111+1;
这个想法是将最高有效位右边的所有位都设置为1,最后+1便是最接近的2的n次幂;
// 0|1=1,1|1=1,0|0 =0;
// decrement n (to handle cases when n itself is a power of 2)
n--;
// Set all bits after the last set bit
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
// increment n and return
return ++n;
文章纯属自我学习!