Github
public static void main(String[] args) {
// num("00000000000000000000000000001011");
// System.out.println("个数---" + numberOfOne(011111000));
}
private static void num(String n) {
int count = 0;
int l = 1;
int e = n.length();
int number = Integer.parseInt(n);
while (l < e && number != 0) {
if (number % 10 == 1) {
count++;
}
number = number / 10;
System.out.println("n = [" + count + "]");
}
}
public static int numberOfOne(int n) {
int result = 0;
for (int i = 0; i < 32; i++) {
/**
* 1&1 =1
* 0&1 =0
*/
result += (n & 1);
System.out.println("n = [" + (n & 1) + "]");
/**
* >>>表示不带符号向右移动二进制数,移动后前面统统补0
*/
n >>>= 1;
}
return result;
}
}
网友评论