> 1; }..."/>
溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

c語言中求解1的個數(shù)

發(fā)布時間:2020-07-25 05:33:56 來源:網(wǎng)絡(luò) 閱讀:349 作者:走走停停吧 欄目:編程語言

在c語言中有三種求解一個數(shù)1的個數(shù)的方法

  1. 將整數(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)

  2. 使整數(shù)與1進(jìn)行與運算,1每次左移一位


    int Numble(int n)

    {

    int count = 0;

    int flag = 1;

    while (flag&n)

    {

    count++;

    flag = flag << 1;

    }

    return count;

    }

  3. 整數(shù)減1在與這個整數(shù)相與


  4. int Numble(int n)

  5. {

  6. int count = 0;

  7. while (n)

  8. {

  9. count++;

  10. n = n&(n - 1);

  11. }

  12. return count;

  13. }

向AI問一下細(xì)節(jié)

免責(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)容。

AI