[Huawei machine trial exercise questions] 45. Calculate the number of 1 in a binary number.
Question
Description: Question title:
Calculate the number of 1 in a binary number. Given a positive integer of the unsigned int type, the binary value indicates the number of "1", which requires the algorithm to be executed as efficiently as possible.
Detailed description:
Prototype:
int GetCount(unsigned int num)
Input parameters:
Positive Integer given by num
Output Parameters (the memory area pointed to by the pointer is valid ):
None
Return Value:
Returns the number of 1. For example, if the input is 13, the corresponding binary value is 1101, and the number of 1 is 3. Then, 3 is returned.
Exercise phase:
Elementary
Code
/* ------------------------------------- * Date: 2015-07-03 * Author: SJF0115 * question: calculate the number of 1 in a binary number * Source: Huawei machine trial exercise subject */# include "OJ. h "# include <iostream> using namespace std;/* Description given a positive integer of the unsigned int type, the number of" 1 "in the binary representation is required, and the algorithm execution efficiency is as high as possible. Prototype int GetCount (unsigned int num) Input Param num the given positive integer Output Param no Return Value returns the number of 1 */int GetCount (unsigned int num) {int x = num; int count = 0; while (x) {x = x & (x-1); ++ count;} // while return count ;}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.