Counting a binary number in java?
Since you do not provide any code, I will give some guilds on how you can do this.
- Get the binary representation of yours
by calling this method
- The previous method will only return the nessecery bits of the number, for example, in case
. 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
and when a
char == 0
will increment the count of zeros. When
char == 1
will the counter increase.
Hope it helps
source to share