#include <iostream>#include <stdio.h>#include <vector>#include <string>using namespace std;/*问题: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的个数。一个简单的方法是n&(n-1),比如7=111,6=110,每一次相与都会把最低位的1给删除掉输入:71101-1输出:330132*/typedef unsigned uint32_t ;class Solution {public: int hammingWeight(uint32_t n) { int count = 0; while(n) { n = n & (n-1); count++; } return count; }};void process(){ vector<int> nums; int value; unsigned num; Solution solution; vector<int> result; while(cin >> num ) { int answer = solution.hammingWeight(num); cout << answer << endl; }}int main(int argc , char* argv[]){ process(); getchar(); return 0;}
新闻热点
疑难解答