卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章19807本站已运行344

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

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

输出

'
Consecutive 1's = 3
卓越飞翔博客
上一篇: C# 程序计算数字中的总位数
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏