![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
Advertisements