介紹:
將整數轉爲二進制,求二進制中有多少個1存在。
解法1:
將整數先轉爲二進制,然後遍歷
public class 有多少個1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
cal_2(n);
}
//方法1,字符串的形式計算
private static void cal_1(int n){
String num = Integer.toBinaryString(n);
int count = 0;
for(int i=0;i<num.length();i++){
if(num.charAt(i) == '1'){
count++;
}
}
System.out.println(count);
}
}
解法2:
將這個數n與(&)上n-1,每次&都會消除掉一個1,最終結果肯定得到0.
private static void cal_2(int n){
int count = 0;
//判斷n是否爲0,如果爲0則說明n中已經沒有1存在了
while(n!=0){
count++;
n=n&(n-1);
//這個是核心,每次進行與運算都會去掉一個1。
}
System.out.println(count);
}
總結:
其實這裏需要掌握的是二進制的一些知識點,例如什麼是與、或、非運算。這些運算有哪些規律,哪些特殊的數字能夠通過這種運算達到想要的目的。例如任何數與1進行與運算,可以獲取到最後一位。等等