【问题标题】:Recursion function to check if bit is set or not (1\0)检查位是否设置的递归函数(1\0)
【发布时间】:2022-01-08 17:41:47
【问题描述】:

我有这个模板,我需要填充空白的地方,函数需要返回(计数)一个数字(x)中的集合(1)位的数量

在这个问题中,一个 int 是 2 个字节,也就是 16 位

模板:

int dlukim(int x, int n, int count)
{
    if (n > 16)
        (1); // return count;
    else
    {
        if ( (2) ) count++;
        (3);// n++; 
        dlukim((4), n, count) // x
    }
}

//之后的内容是我认为应该填充空白空间的内容,但我只是不知道如何处理 2 号空白空间。

【问题讨论】:

  • 这个函数应该做什么? xn 是干什么用的?你能举个例子说明你会如何称呼它以及预期的回报是多少?
  • 缩进对于人们能够阅读和理解代码非常重要。请edit您的问题正确缩进代码。
  • 我现在编辑了帖子,提供了更多信息。我相信 n 可以计算我们检查了多少位以知道何时完成程序。
  • 我相信有 n 可以数...”:所以你没有写那段代码?也许先开始阅读递归理论,然后再问。

标签: c recursion bit-manipulation bitwise-operators


【解决方案1】:

这是很做作的,但是是这样的:

int count_ones(unsigned int x, int count)
{
  /* Base case: zero has no further bits set. */
  if (x == 0)
    return count;
  return count_ones(x >> 1, count + (x & 1));
}

int main(void)
{
    const unsigned int x = 0xfeedf00du;
    printf("%u has %d\n", x, count_ones(x, 0));
    return 0;
}

不确定n 参数,可用于跟踪要检查的位,但我对其进行了优化并始终检查位 0,在递归步骤之间使用右移将所有位移动到该位置。

我还将x 切换为unsigned int,因为在我看来,在关心这些位时,这更“干净”。

【讨论】:

  • 感谢您的回答。我相信你可能是对的,但它必须在我发布的这个模板中。这是我需要完成的任务的一部分
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-25
  • 1970-01-01
  • 2021-03-17
  • 1970-01-01
  • 2015-03-19
  • 1970-01-01
相关资源
最近更新 更多