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;
	}

猜你喜欢

转载自blog.csdn.net/u011243684/article/details/84850439