算法:求一个整数二进制中1的个数

/**
 * 求一个整数二进制中1的个数
 *
 */
public class Binary1Num {

    public static void main(String[] args) {
        int n = 255;
        int count = 0;
        while (n != 0) {
            // 与1做与运算,结果为1则说明个位数是1,然后移位
            if ((n & 1) == 1) {
                count++;
            }
            n >>= 1;
        }
        System.out.println("1的个数为" + count);
    }
}

猜你喜欢

转载自blog.csdn.net/Mr_BJL/article/details/87870623