How many 1s are in the binary representation of a bitwise integer in Chapter 7 of Code Interview Guide for Programmers

topic

整数的二进制表达中有多少个1
package com.lizhouwei.chapter7;

/**
 * @Description: 整数的二进制表达中有多少个1
 * @Author: lizhouwei
 * @CreateDate: 2018/4/26 21:46
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter7_4 {
    public int count(int n) {
        int count = 0;
        while (n != 0) {
            n = n & (n - 1);
            count++;
        }
        return count;
    }
    //测试
    public static void main(String[] args) {
        Chapter7_4 chapter = new Chapter7_4();
        System.out.println("4的二进制中有:"+chapter.count(4)+"个1");
        System.out.println("3的二进制中有:"+chapter.count(3)+"个1");
        System.out.println("15的二进制中有:"+chapter.count(15)+"个1");

    }
}

result

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325044973&siteId=291194637