3

I'm new to java and am wondering if there is any way to count the actual number of ones and zeros in the binary of a single int. For example, I would try and find out the number of 1's and zero's in the binary 32 bit binary of int 6?

trosy
  • 93
  • 3
  • 7
  • Do it the same way you would in any other language you know and wrap the logic in a `main()` in a class. – noMAD Sep 23 '14 at 20:59
  • 2
    See http://stackoverflow.com/a/5263199/3802841 to see how an int can be formatted as a string. Count either the '0's or the '1' and substract the count from the length of the string. – Markus Patt Sep 23 '14 at 21:02

3 Answers3

7

Using Integer.bitcount(int):

int ones = Integer.bitCount(n);
int zeros = Integer.bitCount(~n) - Integer.numberOfLeadingZeros(n);
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
2

Luckily, java has a built in method: Integer.toBinaryString() This takes an integer value, converts it to binary, then returns it as a String.

Or you could brush up on your java skills and create your own method to do it.

DJ Fresh
  • 38
  • 4
1

Since you provide no code i will give some guildines on how you can do it.

  1. Get the binary represesantation of your int by calling this method Integer.toBinaryString(x);
  2. The previous method will return only the nessecery bits of the number for example in the case of 6 it will return 110. But you need a 32 bit representation of 6 so you have to add the extra zeros in front of the result returned from that method.
  3. create 2 counter variables. One for ones and one for zeros.
  4. loop through the characters of your String and when a char == 0 increment the zeros counter. When char == 1 increment the ones counter.

Hope this helps

gkrls
  • 2,618
  • 2
  • 15
  • 29