首页 > 试题广场 >

为了统计一个非负整数的二进制形式中 1 的个数,代码如...

[单选题]
为了统计一个非负整数的二进制形式中 1 的个数,代码如下:
Pascal:
function CountBit(x : longint) : longint;
var
  ret : longint;
begin
  ret := 0;
  while x <> 0 do
  begin
    ret := ret + 1;
    ___________;
  end;
  CountBit := ret;
end;
C++:
int CountBit(int x)
{
    int ret = 0;
    while (x)
    {
        ret++;
        ___________;
    }
    return ret;
}
则空格内要填入的语句是( )。
  • x := x shr 1或者 x >>= 1
  • x := x and (x - 1) 或 x &= x - 1
  • x := x or (x shr 1) 或 x |= x >> 1
  • x := x shl 1 或 x <<= 1
#include<stdio.h>
int bit(int n)
{
    int count=0;
    while(n)
    {
        n=n&(n-1);
        count++;
    }
    return count;
}

int main()
{
    int a=0;
    scanf("%d",&a);
    int count=0;
    count=bit(a);
    printf("%d\n",count);
    return 0;
}

发表于 2023-10-15 19:57:57 回复(0)