Skip to content

Instantly share code, notes, and snippets.

@h2rashee
Created November 20, 2014 17:06
Show Gist options
  • Save h2rashee/faf7bdfcf80031b67bb0 to your computer and use it in GitHub Desktop.
Save h2rashee/faf7bdfcf80031b67bb0 to your computer and use it in GitHub Desktop.
Bit Counting
import java.util.*;
class Bit {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
System.out.println("Bit representation: " + printBits(num));
System.out.println("Number of 1s: " + countBits(num));
}
static int countBits(int num) {
int count = 0;
while(num != 0) {
if((num & 1) != 0) {
count++;
}
num = num >> 1;
}
return count;
}
static String printBits(int num) {
String bits = "";
if(num == 0) {
return "0";
}
while(num != 0) {
if((num & 1) != 0) {
bits = "1" + bits;
} else {
bits = "0" + bits;
}
num = num >> 1;
}
return bits;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment