移位--判斷一個數二進位制表示中1的個數
阿新 • • 發佈:2019-01-30
問題:
給定一個數字,求其二進位制表示中1的個數。
思路:
假設給定數為n, 判斷n&1的結果,如果為1,證明這個數的二進位制表示末位為1,則count+1,然後n右移一位遞迴呼叫這個方法;如果不為1,則count計數不變,n右移一位遞迴呼叫這個方法,直到右移後的這個數為0。
程式碼實現:
public class Test {
public static int count = 0;
public static void main(String[] args) {
System.out.println(getOne(90));
}
public static int getOne(int n) {
int temp = n;
if((temp&1) == 1) {
count++;
getOne(temp>>1);
} else if((temp&1) == 0 && temp !=0) {
getOne(temp>>1);
}
return count;
}
}