判斷int型數(shù)據(jù)中有多少位是1的兩種解法

直接上代碼,代碼中注釋標出算法的特點

package EveryTest.EveryBasic;

/**
 *
 * 統(tǒng)計int型數(shù)據(jù)中有多位是1
 *
 * @author
 * @date 2020/4/28
 */
public class BinaryTest {

    public static void main(String[] args) {

        int num = 11;

        int count1 = countIntBinaryBitIsOneMethod1(num);
        System.out.println(count1);

        int count2 = countIntBinaryBitIsOneMethod2(num);
        System.out.println(count2);
    }

    /**
     *
     * 第一種算法,根據(jù)向右移的特點,如果移掉的是1,那么未移動前的數(shù)據(jù)就是新數(shù)據(jù)的2倍+1
     *
     * 缺陷:
     * 由于最高位是符號位,如果最高位時1的話,那么通過這種算法進行計算會出現(xiàn)錯誤結(jié)果
     * @param num
     * @return
     */
    private static int countIntBinaryBitIsOneMethod1(int num) {
        int count = 0;
        int temp;

        while (true) {
            if (num == 0) {
                break;
            }
            if (num == 1) {
                count++;
                break;
            }

            temp = num;
            num = num >> 1;

            // 判斷被移走的那一位二進制位是否為1
            if (2 * num + 1 == temp) {
                count++;
            }
        }

        return count;
    }

    /**
     * 第二種算法,根據(jù)&按位與的特點,那數(shù)字與1進行&,如果還是1,那么說明最低位是1
     * @param num
     * @return
     */
    private static int countIntBinaryBitIsOneMethod2(int num) {
        int count = 0;

        while (true) {
            if (num == 0) {
                break;
            }
            if ((num & 1) == 1) {
                count++;
            }

            num = num >> 1;
        }

        return count;
    }
}
----------------------------
運行結(jié)果:
3
3
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容