reference:
http://www.geeksforgeeks.org/next-power-of-2/
Problem Definition:
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.
Solution:
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
Code:
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;
}
本文介绍两种高效的方法来找出大于等于给定数的最近的2的幂次方数。第一种方法通过逐步左移的方式找到目标数值;第二种方法采用位操作快速实现。这两种算法对于处理与2的幂有关的问题非常实用。

被折叠的 条评论
为什么被折叠?



