免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
1234下一页
最近访问板块 发新帖
查看: 12336 | 回复: 34
打印 上一主题 下一主题

[算法] 如何使用位操作得到大于N且为2的次方的最小的数 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-06-12 15:27 |只看该作者 |倒序浏览
10可用积分
RT,比如输入10返回16, 输入24返回32,等等.


注意,是使用位操作且没有循环,也不用表驱动等等.

最佳答案

查看完整内容

还有一个比较邪恶的:

论坛徽章:
0
2 [报告]
发表于 2008-06-12 15:27 |只看该作者
还有一个比较邪恶的:

  1. float f = (float)(v - 1);  
  2. return 1 << ((*(unsigned int*)(&f) >> 23) - 126);
复制代码

论坛徽章:
0
3 [报告]
发表于 2008-06-12 15:36 |只看该作者
#include <iostream.h>
int main()
{   int count ;
    int a;
    cin>>a;
    count =0;
    while(a>=1)
    {
      a/=2;         
      count++;
      }
   
    cout<<(1<<count)<<endl;
    system("pause");
   
    }

论坛徽章:
0
4 [报告]
发表于 2008-06-12 15:38 |只看该作者

回复 #2 seraphsky 的帖子

我说了 不用循环....否则我不用费力发这个帖子了.

论坛徽章:
0
5 [报告]
发表于 2008-06-12 15:38 |只看该作者
汇编吧, bsf/bsr

论坛徽章:
0
6 [报告]
发表于 2008-06-12 15:45 |只看该作者
你确定不用循环可以做么
32->2进制的100000还要循环看下后几位是全为0呢

论坛徽章:
0
7 [报告]
发表于 2008-06-12 15:46 |只看该作者
感觉位操作也需要循环。。。。

论坛徽章:
0
8 [报告]
发表于 2008-06-12 16:02 |只看该作者
google搜出来了一个


  1.         // Next Largest Power of 2
  2.         // Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm
  3.         // that recursively "folds" the upper bits into the lower bits. This process yields a bit vector with
  4.         // the same most significant 1 as x, but all 1's below it. Adding 1 to that value yields the next
  5.         // largest power of 2. For a 32-bit value:
  6.         inline_ udword        nlpo2(udword x)
  7.         {
  8.                 x |= (x >> 1);
  9.                 x |= (x >> 2);
  10.                 x |= (x >> 4);
  11.                 x |= (x >> 8);
  12.                 x |= (x >> 16);
  13.                 return x+1;
  14.         }
复制代码

论坛徽章:
0
9 [报告]
发表于 2008-06-12 16:10 |只看该作者
.。。。。。。。。。。。。。。。

[ 本帖最后由 dpsuffix 于 2008-6-12 16:19 编辑 ]

论坛徽章:
0
10 [报告]
发表于 2008-06-12 16:17 |只看该作者
原帖由 jigloo 于 2008-6-12 16:02 发表
google搜出来了一个


        // Next Largest Power of 2
        // Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm
        // that recursively "folds" the upper bi ...

这也算是查表了吧?
如果这样可以,那我用几个if-else也解决了。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP