 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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 find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
To fetch the consecutive 1’s, use the Bitwise Left Shift Operator. Here is our decimal number.
i = (i & (i << 1));
Loop the above until the value of I is 0 and fetch the length using a variable; count here.
while (i != 0) {    i = (i & (i << 1));    count++; } The example we have taken here is 150.
The binary for 150 is 10010110. Therefore, we have two consecutive one’s.
Example
using System; class Demo {    private static int findConsecutive(int i) {       int count = 0;       while (i != 0) {          i = (i & (i < 1));          count++;       }       return count;    }    // Driver code    public static void Main() {       // Binary or 150 is 10010110       Console.WriteLine(findConsecutive(150));    } }  Output
2
Advertisements
 