編寫一個遞歸方法,它返回數N的二進制表示中1的個數。

/* 編寫一個遞歸方法,它返回數N的二進制表示中1的個數。
 */
class Z_Pra_1_5 {
    public static void main(String[] args) {
        int num = 12121;
        System.out.println(Integer.toBinaryString(num));
        System.out.println(count(num));
    }

    public static int count(int n) {
        if (n == 0)
            return 0;
        if (n == 1)
            return 1;
        if (n % 2 == 0)
            return count(n / 2);
        return count(n / 2) + 1;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章