C++ 中計算連續零對的數量


我們有一個從 1 開始的序列生成器。在每一步中,0 變成 10,1 變成 01。因此,在連續的步驟中將發生以下變化:

步驟 1 − 01

步驟 2 − 1001

步驟 3 − 01101001 ……

目標是找到給定步數的連續 0 對的數量。

如果輸入步數為 1,則 0 對的數量為 0;如果輸入步數為 2,則 0 對的數量為 1;如果輸入步數為 3,則 0 對的數量為 1。

步驟 4 − 1001011001101001

步驟 5 − 01101001100101101001011001101001

我們可以觀察到,序列以 2 的冪遞增,並且在長度為 12 之後重複自身,並且每 12 個字元重複一次。因此,這些長度為 12 的序列有 2 對連續的 0。

對於步驟 S,長度為 12 的模式的數量為 2S /12

連續 2 模式數量 = 1(初始)+ 2 X S(對於其餘長度為 12 的重複)

讓我們透過例子來理解。

輸入 − 步數 = 5

輸出 − 連續零對的數量為 − 5

解釋 − 如上所示,第 5 步的序列為 −

Step 5: 01101001100101101001011001101001
Number of pairs of 0’s is 5.
Also with formula : tmp=25
/12= 32/12 = 2, pairs=1+ 2 x 2 = 5

輸入 − 步數 = 10

輸出 − 連續零對的數量為 − 171

解釋 − 使用公式 − tmp=210/12= 1024/12 = 85,pairs=1+ 2 x 85 = 171

下面程式中使用的方法如下

我們將步數作為輸入,並檢查步數是否等於 1,如果是,則連續 0 對的數量為 0。如果步數等於 2 或 3,則此類對的數量為 1。

否則,使用公式 tmp=2input/12 和 pairs=1+2*tmp 計算。

  • 將一個變數 decimal 作為步數的輸入。

  • 函式 Zero_pairs(int decimal) 獲取 decimal 並返回該步的連續零對的數量。

  • 將初始計數設定為 0。

  • 如果 decimal<=1,則返回 0。

  • 如果 decimal==2 或 decimal==3。則返回 1。

  • 否則,計算 temp=(pow(2,decimal))/12 並計算 count 為 2*temp + 1。

  • 返回 count 作為結果。

示例

 線上演示

#include<bits/stdc++.h>
using namespace std;
int Zero_pairs(int decimal){
   int count = 0;
   if(decimal <=1){
      count = 0;
   }
   else if(decimal == 2 || decimal == 3){
      count = 1;
   }
   else{
      int temp = (pow(2, decimal) / 12);
      count = 2 * temp + 1;
   }
   return count;
}
int main(){
   int decimal = 7;
   cout<<"Count of Pairs Of Consecutive Zeros are: "<<Zero_pairs(decimal);
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

Count of Pairs Of Consecutive Zeros are: 21

更新於: 2020年12月2日

239 次檢視

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告

© . All rights reserved.