二進制1的個數

Github

  public static void main(String[] args) {
//        num("00000000000000000000000000001011");
//        System.out.println("個數---" + numberOfOne(011111000));
    }

    private static void num(String n) {
        int count = 0;
        int l = 1;
        int e = n.length();
        int number = Integer.parseInt(n);
        while (l < e && number != 0) {
            if (number % 10 == 1) {
                count++;
            }
            number = number / 10;
            System.out.println("n = [" + count + "]");
        }

    }

    public static int numberOfOne(int n) {
        int result = 0;
        for (int i = 0; i < 32; i++) {
            /**
             * 1&1   =1
             * 0&1   =0
             */
            result += (n & 1);
            System.out.println("n = [" + (n & 1) + "]");
            /**
             * >>>表示不帶符號向右移動二進制數,移動後前面統統補0
             */
            n >>>= 1;
        }
        return result;

    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章