C# 程序检查二进制数中是否有 K 个连续的 1

csharpserver side programmingprogramming更新于 2024/9/24 18:20:00

要检查二进制数中是否有连续的 1,您需要检查 0 和 1。

首先,为 0 和 1 设置一个 bool 数组,即 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

相关文章