Home > Backend Development > C#.Net Tutorial > C# program to check if there are K consecutive 1's in a binary number

C# program to check if there are K consecutive 1's in a binary number

王林
Release: 2023-09-12 15:21:12
forward
721 people have browsed it

C# program to check if there are K consecutive 1s 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};
Copy after login

For 0, set the count to 0 -

if (myArr[i] == false)
   count = 0;
Copy after login

For 1, increment the count and Set result. The Max() method returns the larger of the two numbers -

count++;
res = Math.Max(res, count);
Copy after login

Example

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&#39;s = "+count(myArr, num));
   }
}
Copy after login

Output

Consecutive 1&#39;s = 3
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template