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

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

    Right shift is your friend.

        int input = 64;
        int sample = ( input < 0 ) ? 0 : input;
        int leadingZeros = ( input < 0 ) ? 0 : 32;
    
        while(sample) {
            sample >>= 1;
            --leadingZeros;
        }
        printf("Input = %d, leading zeroes = %d\n",input, leadingZeros);
    

提交回复
热议问题