位运算-Number of 1 Bits(求一个十进制数字,它的二进制表示中有多少个 1(bit))

来源:互联网 发布:长庚医院网络挂号查询 编辑:程序博客网 时间:2024/06/06 08:26

问题描述:

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

思考:

位运算就是两个二进制表示的数字在相应位置上同为1,那么结果在相应位置就是为,否则一致为0.那么n&(n-1)的作用就是把n的二进制表示中,最低位第一个为一的位变为0.
解题方法为:n = n&n-1

代码(java):

public class NumberOf1Bits {public static int hammingWeight(int n) {       int count = 0;while(n != 0){n = n & n-1;count++;}return count;    }/*public static void main(String[] args){System.out.println(hammingWeight(11));}*/}


0 0