Skip to content

Commit de7dbf1

Browse files
authored
Merge pull request ghostmkg#221 from Ansh-Vikalp/Ansh-Vikalp-patch-1
Program to Count Set Bits in a Number
2 parents dbfddce + a936238 commit de7dbf1

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

Important Questions/CountBit.java

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import java.util.*;
2+
3+
public class CountBit {
4+
public static void main(String[] args) {
5+
Scanner sc = new Scanner(System.in);
6+
System.out.print("Enter a number: ");
7+
int n = sc.nextInt(); // Input a number
8+
int count = 0;// set a counter
9+
10+
// Loop to count the set bits in the binary representation of the number
11+
while (n > 0) {// Execute loop unlit no until num becomes 0
12+
count++;
13+
// This operation clears the rightmost set bit in n
14+
// Example: n = 1010 & 1001 clears the last '1' in binar
15+
n = n & (n - 1);
16+
}
17+
System.out.println("Total set bits: " + count);
18+
sc.close();
19+
}
20+
}

0 commit comments

Comments
 (0)