Topic
Description: Topic title:
求某二进制数中1的个数。给定一个unsigned int型的正整数,求其二进制表示中“1”的个数,要求算法的执行效率尽可能地高。
Detailed Description:
Prototype:
int GetCount(unsigned int num)
Input parameters:
num 给定的正整数
Output parameters (the memory area pointed to by the pointer is guaranteed to be valid):
无
return value:
返回1的个数举例:输入13,则对应的二进制是1101,那么1的个数为3个。则:返回3。
Practice Stage:
初级
Code
/* ---------------------------------------* Date: 2015-07-03* sjf0115* title: Number of 1 in a binary number * Source: Huawei Machine Test Exercises----------------- ------------------------*/#include "OJ.h"#include <iostream>using namespace STD;/*description given a positive integer of type unsigned int, the number of "1" in the second binary representation is required, and the execution efficiency of the algorithm is as high as possible. Prototype int getcount (unsigned int num) Input Param num given positive integer output Param no return Value Returns the number of 1 * /intGetCount (unsigned intNUM) {intx = num;intCount =0; while(x) {x = x & (X-1); ++count; }//while returnCount;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Huawei Machine Test exercises]45. To find the number of 1 in a binary number