C# 程式檢查二進位制數中是否包含 K 個連續的 1


要檢查二進位制數中連續的 1,你需要檢查 0 和 1。

首先,為 0 和 1 設定一個布林陣列,即 false 和 true −

bool []myArr = {false, true, false, false, false, true, true, true};

對於 0,將計數設定為 0 −

if (myArr[i] == false)
   count = 0;

對於 1,遞增計數並設定結果。Max() 方法返回兩個數字中較大的那個 −

count++;
res = Math.Max(res, count);

範例

以下是檢查二進位制數中是否存在 K 個連續 1 的範例 −

即時演示

using System;
class MyApplication {
   static int count(bool []myArr, int num) {
      int myCount = 0, res = 0;
      for (int i = 0; i < num; i++) {
         if (myArr[i] == false)
            myCount = 0;
         else {
            myCount++;
            res = Math.Max(res, myCount);
         }
      }
      return res;
   }
   public static void Main() {
      bool []myArr = {false, true, false, false, false, true, true, true};
      int num = myArr.Length;
      Console.Write("Consecutive 1's = "+count(myArr, num));
   }
}

輸出

Consecutive 1's = 3

更新於: 19-Jun-2020

238 次瀏覽

開啟 職業生涯

完成課程以獲得認證

開始學習
廣告
© . All rights reserved.