用C++計算長度為N的二進位制字串個數,其中只有0和1


假設給定一個數字,例如num,任務是計算可以使用給定數字num形成的二進位制字串的個數,這些字串只包含0和1。

二進位制數制是一種數的表示方法。它是數字系統中最流行的一種,廣泛用於數字系統中。二進位制系統用於表示二進位制量,這些量可以用任何只有兩種工作狀態或可能條件的裝置來表示。例如,開關只有兩種狀態:開或關。

在二進位制系統中,只有兩個符號或可能的數字值,即0和1。由任何只有2種工作狀態或可能條件的裝置表示。二進位制字串是包含二進位制值的字串,即只有0或1。

例如

Input − num = 3
Output − count is 8

說明 − 長度為3的二進位制組合有:000、111、001、101、100、110、011、010,共有8個,因此個數為8。

Input − num = 2
Output − count is 4

說明 − 長度為2的二進位制組合有:00、11、01、10,共有4個,因此個數為4。

下面程式中使用的演算法如下:

  • 輸入一個長整型數字,因為數字可以是任意位數。

  • 計算模值 (long long)(le9 + 7)

  • 建立一個函式來計算個數。

  • 宣告一個臨時變數來儲存計數,另一個變數temp並將其初始化為2。

  • 設定num為 temp = temp % mod

  • 開始迴圈,直到num > 0

  • 檢查IF num & 1,則將count設定為 (count * temp)% mod

  • 設定 num = num >> 1

  • 設定 temp = (temp * temp) % mod

  • 返回count

  • 列印結果。

示例

 線上演示

#include <iostream>
using namespace std;
#define ll long long
#define mod (ll)(1e9 + 7)
// An iterative function to find (x^y)%p in O(log y)
ll power(ll x, ll y, ll p){
   ll result = 1;
   x = x % p; // Update x if it is more than or
   // equal to p
   while (y > 0){
      // If y is odd, multiply x with result
      if (y & 1){
         result = (result * x) % p;
      }
      // y must be even now
      y = y >> 1; // y = y/2
      x = (x * x) % p;
   }
   return result;
}
// Function to count the number of binary strings
ll countbstring(ll num){
   int count = power(2, num, mod);
   return count;
}
int main(){
   ll num = 3;
   cout <<"count is: "<<countbstring(num);
   return 0;
}

輸出

如果執行上述程式碼,我們將得到以下輸出:

count is: 8

更新於:2020年5月15日

462 次檢視

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告