C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: The value 0 has no bits set, and the value 1 has just one bit set. The MAX_VALUE has all except the sign bit set (31 bits).
Java program that uses bitCount
public class Program {
public static void main(String[] args) {
// Call bitCount on 0, 1 and MAX_VALUE.
int bits0 = Integer.bitCount(0);
int bits1 = Integer.bitCount(1);
int bitsAll = Integer.bitCount(Integer.MAX_VALUE);
System.out.println(bits0);
System.out.println(bits1);
System.out.println(bitsAll);
}
}
Output
0
1
31
Then: We test the binary string against the bit count. We find the count of "one" values is equal to the result of bit count.
So: The Java built-in code is consistent. Most Java code included is high-quality and well-tested.
Java program that uses bitCount and toBinaryString
import java.util.Random;
public class Program {
public static void main(String[] args) {
Random rand = new Random();
// Generate 10 tests.
for (int i = 0; i < 10; i++) {
// Get a random int.
int value = rand.nextInt(1000);
// Use bitCount and toBinaryString.
int count = Integer.bitCount(value);
String result = Integer.toBinaryString(value);
// Count 1 values in binary string.
int charCount = 0;
for (int z = 0; z < result.length(); z++) {
if (result.charAt(z) == '1') {
charCount++;
}
}
// Print results.
System.out.println(":: TEST ::");
System.out.println("BitCount: " + count);
System.out.println("BinaryString: " + result);
System.out.println("CharCount: " + charCount);
}
}
}
Output
:: TEST ::
BitCount: 4
BinaryString: 101011
CharCount: 4
:: TEST ::
BitCount: 4
BinaryString: 110110000
CharCount: 4
:: TEST ::
BitCount: 6
BinaryString: 1110011010
CharCount: 6
:: TEST ::
BitCount: 4
BinaryString: 1001100010
CharCount: 4
:: TEST ::
BitCount: 5
BinaryString: 1010111000
CharCount: 5
:: TEST ::
BitCount: 7
BinaryString: 1011110101
CharCount: 7
:: TEST ::
BitCount: 7
BinaryString: 111011101
CharCount: 7
:: TEST ::
BitCount: 4
BinaryString: 10011010
CharCount: 4
:: TEST ::
BitCount: 5
BinaryString: 101011010
CharCount: 5
:: TEST ::
BitCount: 4
BinaryString: 101000011
CharCount: 4