C#程序检查二进制数中是否有K个连续的1
要检查二进制数中连续的1,需要检查0和1。
首先,将布尔数组设置为0和1s,即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
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短