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

后端 未结 6 2112
星月不相逢
星月不相逢 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:34

    Using floating points is not the right answer....

    Here is an algo that I use to count the TRAILING 0... change it for Leading... This algo is in O(1) (will always execute in ~ the same time, or even the same time on some CPU).

    int clz(unsigned int i)
    {
      int zeros;
      if ((i&0xffff)==0) zeros= 16, i>>= 16; else zeroes= 0;
      if ((i&0xff)==0) zeros+= 8, i>>= 8;
      if ((i&0xf)==0) zeros+= 4, i>>= 4;
      if ((i&0x3)==0) zeros+= 2, i>>= 2;
      if ((i&0x1)==0) zeros+= 1, i>>= 1;
      return zeroes+i;
    }
    

提交回复
热议问题