Skip to content

Instantly share code, notes, and snippets.

@jinahya
Last active October 20, 2018 04:18
Show Gist options
  • Save jinahya/8ba8c8953e378e943a654535ec0faea6 to your computer and use it in GitHub Desktop.
Save jinahya/8ba8c8953e378e943a654535ec0faea6 to your computer and use it in GitHub Desktop.
Count 1's in a number.
public class BitCounter {
public static void main(final String... args) {
int i = Integer.parseInt(args[0]);
int m = Integer.parseInt(args[1]);
int count = 0;
switch (m) {
case 0:
// iterates 32 regarless of the value
for (int j = 0; j < Integer.SIZE; j++) {
if ((i & 0x01) == 0x01) {
count++;
}
i >>>= 1;
}
break;
case 1:
// iterates for only the number of 1s
for (; i > 0; count++) {
i &= i - 1;
}
break;
default:
// java.lang.Integer#bitCount(i)
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
count = i & 0x3f;
break;
}
System.out.println(count);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment