计算二进制中1的个数

给定一个int 数字,要求计算出int数字对应的二进制中1的个数

输入例子1:

15

输出例子1:

4

import java.util.*;
public class Solution {
    /**
     * 计算int对应二进制中1的个数
     * @param n int整型 数字
     * @return int整型
     */
    public int countBit (int n) {
        // 用n对2取余,结果为1即1的个数+1
        int count = 0;
        while (n > 0) {
            if (n % 2 == 1) {
                count++;
            }
            n /= 2;
        }
        return count;
    }
}
posted @ 2022-06-01 21:52  Autonomy`  阅读(26)  评论(0)    收藏  举报