Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Max Consecutive Set Bits in Bit Manipulation #1773

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions Bit Manipulation/Max Consecutive Set Bits/READ ME.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
## Description
The Max Consecutive Set Bits problem requires finding the longest contiguous sequence of 1s in the binary representation of a given integer. For instance, for the integer 29, whose binary representation is 11101, the longest sequence of consecutive 1s is 3.

### Input
An integer n.

### Output
An integer representing the length of the longest contiguous sequence of 1s in the binary representation of n.

### Constraints

0≤n≤10^9

### Time Complexity
The time complexity is **O(logn)**, which is efficient because we only need to examine each bit in the binary representation of n, which takes at most O(logn) time.
30 changes: 30 additions & 0 deletions Bit Manipulation/Max Consecutive Set Bits/program.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#include <stdio.h>

int maxConsecutiveOnes(int n) {
int maxCount = 0, currentCount = 0;

while (n > 0) {
// Check if the last bit is 1
if (n & 1) {
currentCount++;
if (currentCount > maxCount)
maxCount = currentCount;
} else {
currentCount = 0;
}
// Right shift the bits of n by 1 to check the next bit
n >>= 1;
}
return maxCount;
}

int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);

int result = maxConsecutiveOnes(n);
printf("Maximum consecutive set bits: %d\n", result);

return 0;
}
Loading