[Huawei Machine Test exercises]45. To find the number of 1 in a binary number

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.