开发者

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 kno开发者_如何学JAVAw 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.


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/


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.


As well as Java API methods, there's various bit hacks hiding here that you could use as well, although how well they translate to the Java world I don't know (or for those that do, whether they're any more efficient that calling APIs). See the 'Counting bits set' section.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜