- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

To check for consecutive 1’s in a binary number, you need to check for 0 and 1.

Firstly, set a bool array for 0s and 1s 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 the result. The Max() method returns the larger of two number −

count++; res = Math.Max(res, count);

## Example

The following is the example to check if there are K consecutive 1’s in a binary number −

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)); } }

## Output

Consecutive 1's = 3

- Related Questions & Answers
- Python program to check if there are K consecutive 1’s in a binary number?
- C/C++ Program to Count number of binary strings without consecutive 1’s?
- Program to Count number of binary strings without consecutive 1’s in C/C++?
- Count Binary String without Consecutive 1's
- Count number of binary strings without consecutive 1's in C
- Finding maximum number of consecutive 1's in a binary array in JavaScript
- Check If All 1's Are at Least Length K Places Away in C++
- Python Program to Count number of binary strings without consecutive 1’
- Program to find longest consecutive run of 1 in binary form of a number in C++
- 1’s and 2’s complement of a Binary Number?
- Check if array elements are consecutive in Python
- Check if a binary string contains consecutive same or not in C++
- C# program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
- Python program to find the length of the largest consecutive 1's in Binary Representation of a given string.
- Java program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer

Advertisements