UC校园招聘C++工程师笔试题

匿名网友 匿名网友 发布于: 2015-08-30 00:00:00
阅读 155 收藏 0 点赞 0 评论 0

要求根据代码分析代码的功能:
unsigned int CountOne(unsigned int x){
x = (x & 0x55555555) + (x >> 1 & 0x55555555);
x = (x & 0x33333333) + (x >> 2 & 0x33333333);
x = (x & 0x0f0f0f0f) + (x >> 4 & 0x0f0f0f0f);
x = (x & 0x00ff00ff) + (x >> 8 & 0x00ff00ff);
x = (x & 0x0000ffff) + (x >> 16 & 0x0000ffff);
return x;
}
就这么多。
经过检验,这是检验的代码:
#include<iostream>
using namespace std;
unsigned int CountOne(unsigned int x);
int main(){
unsigned int x;
cout<<“Input a num and will return the count of one:”<<endl;
cout<<“(like input 211,and result:5)”<<endl;
cin>>x;
cout<<“result:”<<endl;
cout<<CountOne(x)<<endl;
return 0;
}
unsigned int CountOne(unsigned int x){
x = (x & 0x55555555) + (x >> 1 & 0x55555555);
x = (x & 0x33333333) + (x >> 2 & 0x33333333);
x = (x & 0x0f0f0f0f) + (x >> 4 & 0x0f0f0f0f);
x = (x & 0x00ff00ff) + (x >> 8 & 0x00ff00ff);
x = (x & 0x0000ffff) + (x >> 16 & 0x0000ffff);
return x;
}
该函数就是计算一个32位无符号整数中含有1的个数,就5行代码。

评论列表
文章目录