1 package cn.test;
2
3 public class Test07 {
4 /*
5 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
6 */
7 /*
8 思路:a&(a-1)的结果会将a最右边的1变为0,直到a = 0,还可以先将a&1 != 0,然后右移1位,但不能计算负数的值,
9 */
10
11 public static void main(String[] args) {
12
13 Test07 test07 = new Test07();
14 // System.out.println(7&6);
15 System.out.println(test07.NumberOf1(-10));
16 //验证上面的结果
17 String str = Integer.toBinaryString(-10);
18 int sum = 0;
19 for (int j = 0; j < str.length(); j++) {
20 if(str.charAt(j) == '1') {
21 sum++;
22 }
23 }
24
25 System.out.println(sum);
26 }
27
28 public int NumberOf1(int n) {
29 //思路:a&(a-1)的结果会将a最右边的1变为0,直到a = 0,还可以先将a&1 != 0,然后右移1位,但不能计算负数的值,
30
31 int countOfOne = 0;
32 while(n != 0) {
33 countOfOne ++;
34 n = n & (n - 1);
35 }
36 return countOfOne;
37 }
38 }