求一個32位整數中1個個數

public static int getOneCount(int num) {
		/**
		 * 思路爲:每次向右移動一位,而後與1相與,
		 * */
		int oneCount = 0;
		do {
			if((num & 1) != 0){
				++oneCount;
			}
		} while ((num >>>= 1) != 0);
		/**必須用num>>>=1(無符號右移),而不能用num>>=1(有符號右移), 
		 * 由於當參數爲負數時,有符號右移老是在高位插入1,致使死循環 **/
		
		return oneCount;
	}
相關文章
相關標籤/搜索