標(biāo)題:
C語言算法:你的代碼是否高效?
[打印本頁]
作者:
heise
時間:
2014-8-19 18:04
標(biāo)題:
C語言算法:你的代碼是否高效?
1、寫一個高效C語言程序,計算一個無符號整數(shù)中1的個數(shù)
0000----------0
0100----------1
1001----------2
1111----------4
一般思路肯定是循環(huán)右移判斷與0x0001相與的結(jié)果是否為1。
算法如下:
unsigned char count; unsigned int x;
for ( count=0; x; count++)
x&=x-1;
最后循環(huán)的次數(shù)count 就是無符號int型數(shù)據(jù)中1的個數(shù)。
若求比特0的個數(shù),則程序修改如下(16位單片機(jī)):
unsigned char count; unsigned int x;
for ( count=16; x; count--)
x&=x-1;
歡迎光臨 (http://www.torrancerestoration.com/bbs/)
Powered by Discuz! X3.1