diff --git a/Bit Manipulation/Max Consecutive Set Bits/READ ME.md b/Bit Manipulation/Max Consecutive Set Bits/READ ME.md new file mode 100644 index 00000000..7c982966 --- /dev/null +++ b/Bit Manipulation/Max Consecutive Set Bits/READ ME.md @@ -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. diff --git a/Bit Manipulation/Max Consecutive Set Bits/program.c b/Bit Manipulation/Max Consecutive Set Bits/program.c new file mode 100644 index 00000000..580a748e --- /dev/null +++ b/Bit Manipulation/Max Consecutive Set Bits/program.c @@ -0,0 +1,30 @@ +#include + +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; +}