首頁  >  文章  >  後端開發  >  C#程式檢查二進制數中是否有K個連續的1

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

王林
王林轉載
2023-09-12 15:21:12607瀏覽

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

要檢查二進位數中是否有連續的 1,需要檢查 0 和 1。

首先,為0 和1 設定一個bool 陣列即假與真-

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&#39;s = "+count(myArr, num));
   }
}

輸出

Consecutive 1&#39;s = 3

以上是C#程式檢查二進制數中是否有K個連續的1的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除