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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP