用C語言計算沒有連續1的二進位制字串個數
任務是計算長度為n且沒有連續1的二進位制字串的總數。
二進位制數系統是一種數字表示技術。它是數字系統中最流行和最常用的。二進位制系統用於表示二進位制數量,這些數量可以用任何只有兩種工作狀態或可能條件的裝置來表示。例如,開關只有兩種狀態:開或關。
在二進位制系統中,只有兩個符號或可能的數字值,即0和1。由任何只有2種工作狀態或可能條件的裝置表示。二進位制字串是指包含二進位制值(即0或1)的字串。
讓我們用一個例子來理解我們必須做什麼:
輸入 - n = 2
輸出 - 長度為2且沒有連續1的二進位制字串的個數是:3
解釋 - 00、01、10,所以只有3個長度為n且沒有連續1的二進位制字串。
輸入 - n = 7
輸出 - 長度為7且沒有連續1的二進位制字串的個數是 - 34
下面程式中使用的方法如下:
輸入字串長度n。
在count函式中,我們將計算沒有連續1的二進位制字串,定義兩個大小為n的陣列arr[]和arr_2,以及一個變數temp來儲存結果。
將兩個陣列的第0個元素賦值為1。
迴圈從i=1到i小於n。
在迴圈中,設定arr[i] = arr[i-1]+arr_2[i-1] 和 arr_2[i] = arr[i-1]。
設定temp = arr[n-1]+arr_2[n-1],然後列印temp。
示例
#include<stdio.h>
//create function to calculate binary strings without consecutive 1’s
void count(int num){
int arr[num];
int arr_2[num];
int i=0, temp=0;
arr[0] = arr_2[0] = 1;
//loop till number isn't equals to 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("
");
}
int main(){
//call the count function
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
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP