我创建了一个程序,该程序应该接收一个整数并返回该数字的二进制表示形式。现在我想添加一个函数来计算数字中有多少个“1”,这就是我遇到一些麻烦的地方,例如:
输入:123 -> 0b01111011 -> 4(因为“1”附近有4个)
为此,我需要将当前脚本的输出存储在一个变量中,但我不能超出这个范围,因为我正在使用 putchar:
#include <stdio.h>
void displayBits(unsigned int value); // prototype
int main(void)
{
unsigned int x; // variable to hold user input
printf("%s", "Enter a nonnegative int: ");
scanf("%u", &x);
displayBits(x);
}
// display bits of an unsigned int value
void displayBits(unsigned int value)
{
// define displayMask and left shift 31 bits
unsigned int displayMask = 1 << 7;
printf("%10u = ", value);
printf("0b");
// loop through bits
for (unsigned int c = 1; c <= 8; ++c) {
putchar(value & displayMask ? '1' : '0');
value <<= 1;
}
putchar('\n');
}
最佳答案
如果您想要计算设置为 1 的相邻位的最大数量,可以按如下方式进行。
有一个计数器可以记录您找到的连续“1”位的数量。当您找到“1”时,将其递增,当您找到“0”时,将其设置为 0。您还需要一个变量来跟踪最长的运行。如果当前大于最长运行,则将最长设置为当前。
int current_run = 0, longest_run = 0;
while (displayMask) {
if (value & displayMask) {
current_run++;
if (current_run > longest_run) {
longest_run = current_run;
}
putchar('1');
} else {
current_run = 0;
putchar('0');
}
displayMask >>= 1;
}
关于c - 显示数字的位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51974413/