diff --git a/Bit Manipulation/Count set bits/README.md b/Bit Manipulation/Count set bits/README.md new file mode 100644 index 00000000..420a5cd0 --- /dev/null +++ b/Bit Manipulation/Count set bits/README.md @@ -0,0 +1,20 @@ +# Count the Number of Set Bits + +## Description +This algorithm counts the number of 1 bits (set bits) in the binary representation of a given integer. Counting set bits is useful in various fields like cryptography, networking, and data compression. + +## Example Usage +Enter an integer: 29 +Number of set bits in 29 is 4 + +## Complexity +** Time Complexity **: +O(number of set bits) — The loop runs once for each set bit. + +** Space Complexity **: +O(1) — Constant space usage. + +## Applications +- Cryptography: For analyzing binary data. +- Networking: Useful for IP address and network mask operations. +- Data Compression: Helps in efficient data encoding and decoding \ No newline at end of file diff --git a/Bit Manipulation/Count set bits/program.c b/Bit Manipulation/Count set bits/program.c new file mode 100644 index 00000000..dc2a5ce5 --- /dev/null +++ b/Bit Manipulation/Count set bits/program.c @@ -0,0 +1,21 @@ +#include + +int countSetBits(int n) { + int count = 0; + while (n > 0) { + n = n & (n - 1); // Removes the rightmost set bit + count++; + } + return count; +} + +int main() { + int num; + printf("Enter an integer: "); + scanf("%d", &num); + + int result = countSetBits(num); + printf("Number of set bits in %d is %d\n", num, result); + + return 0; +}