您的位置:首页 > 其它

逻辑运算小结1---和X拥有的1的个数相同,但是比X大的第一个数的求解方法

2016-12-12 22:17 239 查看
#include <iostream>

using namespace std;
//和X拥有的1的个数相同,但是比X大的第一个数的求解方法:
unsigned snoob(unsigned x)    //举例:  X = 0000 1111 00000
{
unsigned smallest, ripple, ones;        // x = 0000 1111 0000
smallest = x & -x;                     // 0000 0001 0000
ripple = x + smallest;                // 0001 0000 0000
ones = x ^ ripple;                   // 0001 1111 0000
ones = (ones >> 2) / smallest;      // 0000 0000 0111
return ripple | ones;               // xxx1 0000 0111
}
int main()
{
unsigned  int x;
cin>>x;
cout<<snoob(x)<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Hacker Delight
相关文章推荐