-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuestion15.java
More file actions
38 lines (35 loc) · 849 Bytes
/
Question15.java
File metadata and controls
38 lines (35 loc) · 849 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package question;
/**
* 二进制中1的个数
* 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
*
* @author ahscuml
* @date 2018/9/19
* @time 18:25
*/
public class Question15 {
public static void main(String[] args) {
System.out.println(NumberOf1(0));
System.out.println(NumberOf1(4));
System.out.println(NumberOf1(7));
}
/*public static int NumberOf1(int n) {
int count = 0;
while(n != 0){
n = n & (n - 1);
count++;
}
return count;
}*/
public static int NumberOf1(int n) {
int count = 0;
int flag = 1;
while (flag != 0) {
if ((n & flag) != 0) {
count++;
}
flag = flag << 1;
}
return count;
}
}