Next Power of 2
来源:互联网 发布:linux telnet 端口测试 编辑:程序博客网 时间:2024/06/08 16:47
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;}
- Next Power of 2
- Leetcode 231 and 342. Power of 2, Power of 4
- power of 2 or not
- poj 2406 Power Strings next[]
- Power Strings next数组应用
- TestNg--The next generation of testing--2
- n is a power of 2 ?
- The Power of Java 7 NIO.2
- [刷题]O(1) Check Power of 2
- O(1) Check Power of 2
- lintcode: O(1) Check Power of 2
- *[Lintcode]O(1) Check Power of 2
- 231. Power of Two(2)
- Mod of power 2 on bitwise operators?
- Leetcode-Power of 2,3,4
- #142 O(1) Check Power of 2
- [Microsoft] O(1) Check Power of 2
- Power of two,power of three,power of four
- eclipse启动参数里设置jvm大小
- javascript获取下拉列表多个选项值
- Ubuntu 12.04 Precise LTS: Install ModSecurity for Apache 2 web server
- 黑马程序员之编写对class文件进行加密的工具类
- Linux多任务编程(二)---fork()函数及其基础实验
- Next Power of 2
- 设计模式(17)---->中介者模式
- Chrome浏览器插件开发心得
- Linux Kbuild工作原理分析(以DVSDK生成PowerVR显卡内核模块为例)
- WEB架构师成长之路之一-走正确的路
- linux shell自动变量$#,$@,$0,$1,$2
- 项目开发流程(期间使用的UML图表)
- ACE学习(二)原子操作与ACE_Atomic_Op
- Configure on host for network bridge