k*****2 发帖数: 252 | 1 已知一个整数x,有以下几点前提说明
1,可正可负
2,未知具体大小:可能是16bits,也可能是128bits甚至更多,不局限于某个特定数
3,不准用sizeof
输出:
写个算法,统计含1的bit位数目
这题我被面到了,大家可以参考的想一想哈 |
h*******u 发帖数: 15326 | 2 int one = 1;
int t = x&1;
while(one>0)
{
x = x>>1;
t += x&1;
one=one<<1;
}
std::cout<<"# of 1 = "<
【在 k*****2 的大作中提到】 : 已知一个整数x,有以下几点前提说明 : 1,可正可负 : 2,未知具体大小:可能是16bits,也可能是128bits甚至更多,不局限于某个特定数 : 3,不准用sizeof : 输出: : 写个算法,统计含1的bit位数目 : 这题我被面到了,大家可以参考的想一想哈
|
d**e 发帖数: 6098 | 3 其实可以不需要 one 吧,直接 while(x > 0)
还是one是用来算是多少bit?
【在 h*******u 的大作中提到】 : int one = 1; : int t = x&1; : while(one>0) : { : x = x>>1; : t += x&1; : one=one<<1; : } : std::cout<<"# of 1 = "<
|
k*****2 发帖数: 252 | 4 才发现,是用one的左移来解决高位补1的问题,不错
我个人觉得stl的bitset用的查表法可以算一个思路,不过先要弄个while(one<<=1)++
size;这样的语句知道int的size
【在 h*******u 的大作中提到】 : int one = 1; : int t = x&1; : while(one>0) : { : x = x>>1; : t += x&1; : one=one<<1; : } : std::cout<<"# of 1 = "<
|
g**u 发帖数: 583 | 5 int count(int a)
{
int counter=0;
while(a)
{
a=a&(a-1); //set the last 1 to 0
counter++;
}
return counter;
} |
h****r 发帖数: 2056 | 6 This is the standard answer.
【在 g**u 的大作中提到】 : int count(int a) : { : int counter=0; : while(a) : { : a=a&(a-1); //set the last 1 to 0 : counter++; : } : return counter; : }
|
k*****2 发帖数: 252 | 7 这种如果没看过Hacker's Delight这书,能当场想出来的算牛人了
如果有很多位1,那还是查表快
【在 g**u 的大作中提到】 : int count(int a) : { : int counter=0; : while(a) : { : a=a&(a-1); //set the last 1 to 0 : counter++; : } : return counter; : }
|