How To Find The Leading Number Of Zero's In a Number using C

后端 未结 6 2110
星月不相逢
星月不相逢 2021-02-04 21:07

for example,if i have number 64,then its binary representation would be 0000 0000 0000 0000 0000 0000 0100 0000 so leading number of zero\'s is 25. remember i have to calculate

6条回答
  •  礼貌的吻别
    2021-02-04 21:29

    Because the logarithm base 2 roughly represents the number of bits required to represent a number, it might be useful in the answer:

    irb(main):012:0> 31 - (Math::log(64) / Math::log(2)).floor()
    => 25
    irb(main):013:0> 31 - (Math::log(65) / Math::log(2)).floor()
    => 25
    irb(main):014:0> 31 - (Math::log(127) / Math::log(2)).floor()
    => 25
    irb(main):015:0> 31 - (Math::log(128) / Math::log(2)).floor()
    => 24
    

    Of course, one downside to using log(3) is that it is a floating-point routine; there are probably some supremely clever bit-tricks to find the number of leading zero bits in integers, but I can't think of one off the top of my head...

提交回复
热议问题