-
Notifications
You must be signed in to change notification settings - Fork 34
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #88 from Ansh-Vikalp/patch-1
Program to Count Set Bits in a Number
- Loading branch information
Showing
3 changed files
with
72 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters