不含连续1的二进制字符串计数
在这个问题中,我们需要找到一些不包含连续1的二进制数。在3位二进制字符串中,有三个二进制数011、110、111包含连续的1,而有五个数字不包含连续的1。因此,将此算法应用于3位数字后,答案将为5。
如果a[i]是位数为I且不包含任何连续1的二进制数的集合,而b[i]是位数为I且包含连续1的二进制数的集合,那么存在如下递归关系
a[i] := a[i - 1] + b[i - 1] b[i] := a[i - 1]
输入和输出
Input: This algorithm takes number of bits for a binary number. Let the input is 4. Output: It returns the number of binary strings which have no consecutive 1’s. Here the result is: 8. (There are 8 binary strings which has no consecutive 1’s)
算法
countBinNums(n)
输入:n是位数。
输出 − 计算有多少个数字不包含连续的1。
Begin define lists with strings ending with 0 and ending with 1 endWithZero[0] := 1 endWithOne[0] := 1 for i := 1 to n-1, do endWithZero[i] := endWithZero[i-1] + endWithOne[i-1] endWithOne[i] := endWithZero[i-1] done return endWithZero[n-1] + endWithOne[n-1] End
示例
#include <iostream>
using namespace std;
int countBinNums(int n) {
int endWithZero[n], endWithOne[n];
endWithZero[0] = endWithOne[0] = 1;
for (int i = 1; i < n; i++) {
endWithZero[i] = endWithZero[i-1] + endWithOne[i-1];
endWithOne[i] = endWithZero[i-1];
}
return endWithZero[n-1] + endWithOne[n-1];
}
int main() {
int n;
cout << "Enter number of bits: "; cin >> n;
cout << "Number of binary numbers without consecitive 1's: "<<countBinNums(n) << endl;
return 0;
}输出
Enter number of bits: 4 Number of binary numbers without consecitive 1's: 8
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP