Skip to content

Instantly share code, notes, and snippets.

@DTrejo
Created November 4, 2010 16:39
Show Gist options
  • Save DTrejo/662753 to your computer and use it in GitHub Desktop.
Save DTrejo/662753 to your computer and use it in GitHub Desktop.
public class Bitops {
// Takes a character and returns the number of ones
// contained in its binary representation
static int numOnes(char c) {
int hex = (int) c;
int sum = 0;
// we want unsigned comparison
// this works fine if java uses 2s complement (it does I think).
while (hex > 0) {
sum += hex & 0x1; // loops a maximum of 8 times
hex = hex >> 1; // signed shift.
}
return sum;
}
// n = length of the string str
// O(n * 8) where 8 is the number of bits per character.
static int numOnesInString(String str){
int sum = 0;
while (str.length() > 0){
char firstChar = str.charAt(0);
sum += numOnes(firstChar);
str = str.substring(1);
}
return sum;
}
public static void main(String[] args) {
System.out.println(numOnesInString(" ") == 2); // Each space is 0x20, which has one 1 bit in it.
System.out.println(numOnesInString("\0") == 0); // Null character is 0x00, which has no 1 bits in it.
System.out.println(numOnesInString("H") == 2); // H is 01001000, which has two 1 bits in it.
System.out.println(numOnesInString("z") == 5); // z is 01111010, which has five 1 bits in it.
System.out.println(numOnesInString("Hi") == 6); // i is 01101001, which has four 1 bits in it (then add two for H).
String str = "\n# of ones in \0this string is what?";
System.out.println(str);
System.out.println(numOnesInString(str));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment