Created
November 20, 2014 17:06
-
-
Save h2rashee/faf7bdfcf80031b67bb0 to your computer and use it in GitHub Desktop.
Bit Counting
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
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