二进制中 1 的个数
题目形容
输出一个整数,输入该数32位二进制示意中1的个数。其中正数用补码示意。
题目链接: 二进制中 1 的个数
代码
/** * 题目:二进制中 1 的个数 * 题目形容 * 输出一个整数,输入该数32位二进制示意中1的个数。其中正数用补码示意。 * 题目链接: * https://www.nowcoder.com/practice/8ee967e43c2c4ec193b040ea7fbb10b8?tpId=13&&tqId=11164&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking */public class Jz11 { public static void main(String[] args) { System.out.println(numberOf1(10)); System.out.println(numberOf2(10)); } /** * n&(n-1) * 该位运算去除 n 的位级示意中最低的那一位。 * n : 10110100 * n-1 : 10110011 * n&(n-1) : 10110000 * * @param n * @return */ public static int numberOf1(int n) { int cnt = 0; while (n != 0) { cnt++; n &= n - 1; } return cnt; } /** * 库办法 * * @param n * @return */ public static int numberOf2(int n) { return Integer.bitCount(n); }}
【每日寄语】 你的微笑是最有治愈力的力量,胜过世间最美的风光。