Counting a binary number in java?
I'm new to java and I'm wondering if there is a way to count the actual number of ones and zeros in a single int binary. For example, would I try to find out the number 1 and zero in a binary 32 bit binary int 6?
+3
trosy
source
to share
3 answers
Using Integer.bitcount(int)
:
int ones = Integer.bitCount(n);
int zeros = Integer.bitCount(~n) - Integer.numberOfLeadingZeros(n);
+7
Jean Logeart
source
to share
Luckily java has a built-in method: Integer.toBinaryString () This takes an integer value, converts it to binary and then returns it as a string.
Or you can brush up on your java skills and create your own method for this.
+1
DJ Fresh
source
to share
Since you do not provide any code, I will give some guilds on how you can do this.
- Get the binary representation of yours
int
by calling this methodInteger.toBinaryString(x);
- The previous method will only return the nessecery bits of the number, for example, in case
6
it will110
. But you need 32-bit representation 6, so you need to add extra zeros before the result returned by this method. - create 2 variable counters. One for one and one for zeros.
- loop through the characters of your
String
and when achar == 0
will increment the count of zeros. Whenchar == 1
will the counter increase.
Hope it helps
0
qbit
source
to share