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