Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count set bits in float in Java

This is an interview question: how to count set bits in float in Java ? I guess I should not know the bit representation of float to answer this question. Can I just convert a float to a byte array somehow? I can use the Java serialization but it looks like overkill.

like image 378
Michael Avatar asked Jan 27 '26 12:01

Michael


2 Answers

The Float class has an:

    public static int floatToIntBits(float value)

method that returns a representation of the specified floating-point value according to the IEEE 754 floating-point "single format" bit layout.

So you can get the bits with this method, then count which ones are set.

http://download.oracle.com/javase/7/docs/api/

like image 75
Hunter McMillen Avatar answered Jan 30 '26 04:01

Hunter McMillen


You can use:

Integer.bitCount(Float.floatToIntBits(value))

Having said that it's a very bad interview question...... seems to rely more on knowing specifics of the Java API which is not what you should be using as a basis for hiring. You want someone who understands the principles and knows how to look the details up when needed, not someone who just memorises APIs.

like image 33
mikera Avatar answered Jan 30 '26 03:01

mikera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!