Home > Article > Backend Development > C# program to check if there are K consecutive 1's in a binary number
To check whether there are consecutive 1's in a binary number, you need to check 0 and 1.
First, set up an array of bools for 0 and 1 i.e. false and true -
bool []myArr = {false, true, false, false, false, true, true, true};
For 0, set the count to 0 -
if (myArr[i] == false) count = 0;
For 1, increment the count and Set result. The Max() method returns the larger of the two numbers -
count++; res = Math.Max(res, count);
The following is an example of checking whether there are K consecutive 1's in a binary number-
Site Demo
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
The above is the detailed content of C# program to check if there are K consecutive 1's in a binary number. For more information, please follow other related articles on the PHP Chinese website!