计算C中没有连续1的二进制字符串的数目
输出-没有连续1的7的二进制字符串的计数是-34
在以下程序中使用的方法如下
输入n作为字符串长度
在count函数中,我们将对不具有连续1的二进制字符串进行计数,定义两个大小为n的数组arr[]和arr_2,以及一个变量temp来存储结果。
将两个数组的第0个元素分配为1
从i=1循环直到我小于n。
循环时,设置arr[i]=arr[i-1]+arr_2[i-1]和arr_2[i]=arr[i-1]
设置温度=arr[n-1]+arr_2[n-1],然后打印该温度。
示例
#include<stdio.h>
//创建函数以计算不带连续1的二进制字符串
void count(int num){
int arr[num];
int arr_2[num];
int i=0, temp=0;
arr[0] = arr_2[0] = 1;
//循环直到数字不等于0-
for (i = 1; i < num; i++){
arr[i] = arr[i-1] + arr_2[i-1];
arr_2[i] = arr[i-1];
}
temp = arr[num-1] + arr_2[num-1];
printf("Count of binary strings without consecutive 1’s of %d is : %d",num,temp);
printf("\n");
}
int main(){
//调用计数功能
count(10);
count(7);
count(1);
return 0;
}输出结果
如果运行上面的代码,我们将获得以下输出-
Count of binary strings without consecutive 1’s of 10 is : 144 Count of binary strings without consecutive 1’s of 7 is : 34 Count of binary strings without consecutive 1’s of 1 is : 2