To count minor zeros in Java, you can use this algorithm:
public static int countNonleadingZeroBits(int i) { int result = 0; while (i != 0) { if (i & 1 == 0) { result += 1; } i >>>= 1; } return result; }
This algorithm will be fast enough if your inputs are usually small, but if your input is usually larger, it might be faster to use one of the bit-hack algorithms on this page .
source share