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 Algorithm: Bit Manipulation - Count Set Bits #1352

Merged
merged 5 commits into from
Oct 29, 2024
Merged
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
20 changes: 20 additions & 0 deletions Bit Manipulation/Count set bits/README.md
Original file line number Diff line number Diff line change
@@ -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
21 changes: 21 additions & 0 deletions Bit Manipulation/Count set bits/program.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#include <stdio.h>

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;
}