描述
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;
class Solution { public: /** * @param n: an unsigned integer * @return: the number of ’1' bits */ int hammingWeight(unsigned int n) { // write your code here int sum=0; while(n>0){ n=n&(n-1); sum++; } return sum; } };