首页 > 学院 > 开发设计 > 正文

leecode 解题总结:191. Number of 1 Bits

2019-11-08 00:59:01
字体:
来源:转载
供稿:网友
#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;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表