1. 程式人生 > >leetcode Number of 1 Bits

leetcode Number of 1 Bits

Number of 1 Bits 

10進位制數轉化為二進位制數1的個數

解題思路:n=n&n-1 每一次會消去一個1,只需要統計這個操作出現的次數就可以了。

例如:

n = 0x110100 n-1 = 0x110011 n&(n - 1) = 0x110000 
n = 0x110000 n-1 = 0x101111 n&(n - 1) = 0x100000 
n = 0x100000 n-1 = 0x011111 n&(n - 1) = 0x0 

public static void main(String[] args) {
		int n=11;
		int result = hammingWeight(n);
		System.out.println(result);

	}
	public static int hammingWeight(int n) {
		int count=0;
		while(n!=0){
			n=n&n-1;
			count++;
		}
		return count;
	}