> 1; }..."/>
您好,登錄后才能下訂單哦!
在c語言中有三種求解一個數(shù)1的個數(shù)的方法
將整數(shù)每次右移一位的方式
int Numble(int n)
{
int count = 0;
while (n)
{
if (n & 1 == 1)
count++;
n = n >> 1;
}
return count;
}
但這種方法存在的不足是,當(dāng)這個整數(shù)是負(fù)數(shù)的時候,將無限循環(huán)
使整數(shù)與1進(jìn)行與運算,1每次左移一位
int Numble(int n)
{
int count = 0;
int flag = 1;
while (flag&n)
{
count++;
flag = flag << 1;
}
return count;
}
整數(shù)減1在與這個整數(shù)相與
int Numble(int n)
{
int count = 0;
while (n)
{
count++;
n = n&(n - 1);
}
return count;
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。