# Counting a binary number in java?

3 answers

Using `Integer.bitcount(int)`

:

```
int ones = Integer.bitCount(n);
int zeros = Integer.bitCount(~n) - Integer.numberOfLeadingZeros(n);
```

+7

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 method`Integer.toBinaryString(x);`

- The previous method will only return the nessecery bits of the number, for example, in case
`6`

it will`110`

. 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 a`char == 0`

will increment the count of zeros. When`char == 1`

will the counter increase.

Hope it helps

0

source to share