本文共 1040 字,大约阅读时间需要 3 分钟。
Write a function that, for a given no n, finds a number p which is greater than or equal to n and is a power of 2.
1.Shift result one by one, this is straight-forward
2.Customized and Fast
2.1. Subtract n by 1 n = n -1 2.2. Set all bits after the leftmost set bit. /* Below solution works only if integer is 32 bits */ n = n | (n >> 1); n = n | (n >> 2); n = n | (n >> 4); n = n | (n >> 8); n = n | (n >> 16); 2.3. Return n + 1
1.Shift result one by one, this is straight-forward unsigned int nextPowerOf2(unsigned int n){ unsigned int p = 1; if (n & !(n & (n - 1))) return n; while (p < n) { p <<= 1; } return p;} 2.Customized and Fast
/* Finds next power of two for n. If n itself is a power of two then returns n*/ unsigned int nextPowerOf2(unsigned int n){ n--; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; n++; return n;}
转载地址:http://cexti.baihongyu.com/