gpt4 book ai didi

c - 生成所有长度为n且设置k位的二进制字符串。(需要写在C上)

转载 作者:行者123 更新时间:2023-11-30 17:45:22 26 4
gpt4 key购买 nike

请帮我解决这个任务:生成所有长度为n且设置k位的二进制字符串。(需要写在C上)例如:

n=5
k=3
11100
00111
11010
01011
**01110
11001
10011
**01101
**10110
10101

** 无法生成这些排列

代码:

#include <stdio.h>
#define N 10
int main (void)
{
int mas[N]={0},kst,m,n1,z,a,b;
printf("\n\nVvedit` rozmirnist` masyvu: ");
scanf("%d",&kst);
printf("\n\nVvedit` kil`kist` odynyc`: ");
scanf("%d",&n1);
for(m=0;m1;m++)
mas[m]=1;
for(m=0;m<kst;m++)
printf("%d",mas[m]);
printf("\n");
for(m=0;m<n1;m++){
for(z=0;z<(kst-1);z++)
if((mas[z]==1) && (mas[z+1]==0)){
a=mas[z];
mas[z]=mas[z+1];
mas[z+1]=a;
for(b=0;b<kst;b++)
printf("%d",mas[b]);
printf("\n");

}
}

return 0;
}

最佳答案

这个问题我已经解决了!请在下面找到我的代码!我希望这会对您有所帮助。

#include<stdio.h>

int NumberOfBitsSet(int number)
{
int BitsSet = 0;

while(number != 0)
{

if(number & 0x01)
{
BitsSet++;
}
number = number >> 1;
}

return BitsSet;
}

void PrintNumberInBinary(int number, int NumBits)
{
int val;
val = 1 << NumBits; // here val is the maximum possible number of N bits with only MSB set

while(val != 0)
{
if(number & val)
{
printf("1");
}
else
{
printf("0");
}

val = val >> 1;
}
}

int main()
{
int n,k,i;
int max,min;
printf("enter total number of bits and number of bits to be set:\n");
scanf("%d %d", &n, &k);

min = ((1 << k) - 1); //min possible values with k bits set
max = (min << (n-k)); //max possible value with k bits set!
//printf("%d %d", min, max);
for(i=0; i<= max; i++)
{
if(!(i<min))
{
if(NumberOfBitsSet(i) == k)
{
PrintNumberInBinary(i, (n-1));
printf("\n");
}
}
}

return 0;
}

关于c - 生成所有长度为n且设置k位的二进制字符串。(需要写在C上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19652416/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com