Skip to content

Commit

Permalink
Merge pull request #88 from Ansh-Vikalp/patch-1
Browse files Browse the repository at this point in the history
Program to Count Set Bits in a Number
  • Loading branch information
Kushal997-das authored Oct 23, 2024
2 parents 763d11d + e42e089 commit 4dfafaf
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 1 deletion.
21 changes: 21 additions & 0 deletions Beginner Level πŸ“/Count Set Bit in Number/CountBit.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import java.util.*;

public class CountBit {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt(); // Input a number
int count = 0;// set a counter

// Loop to count the set bits in the binary representation of the number
while (n > 0) {// Execute loop unlit no until num becomes 0
count++;
// This operation clears the rightmost set bit in n
// Example: n = 1010 & 1001 clears the last '1' in binar
n = n & (n - 1);
}
System.out.println("Total set bits: " + count);
sc.close();
}

}
43 changes: 43 additions & 0 deletions Beginner Level πŸ“/Count Set Bit in Number/question.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
## Problem Statement
Write a Java program to count the number of set bits (1s) in the binary representation of a given non-negative integer.

### Input
- A single integer `n` where `0 <= n <= 10^9`.

### Output
- The number of set bits (1s) in the binary representation of the integer.

### Example

#### Example 1:
**Input**:
`5`

**Output**:
`2`

**Explanation**:
Binary representation of 5 is `101`, which has 2 set bits.

#### Example 2:
**Input**:
`10`

**Output**:
`2`

**Explanation**:
Binary representation of 10 is `1010`, which has 2 set bits.

#### Example 3:
**Input**:
`0`

**Output**:
`0`

**Explanation**:
Binary representation of 0 is `0`, which has no set bits.

### Constraints
- `0 <= n <= 10^9`
9 changes: 8 additions & 1 deletion Beginner Level πŸ“/data.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
"name": "Kushal Das",
"githubUsername": "Kushal997-das"
},

// Add your details below as above mention
{
"name": "candy",
Expand All @@ -23,6 +22,14 @@
"name": "Priyansh Khare",
"githubUsername": "PriyanshK09"
},
{
"name": "Yahia Nawashi",
"githubUsername": "Dinoguy12349"
},
{
"name": "Ansh Vikalp",
"githubUsername": "Ansh-Vikalp"
},
{
"name": "Ayesha",
"githubUsername": "Ayesha19297"
Expand Down

0 comments on commit 4dfafaf

Please sign in to comment.