[Huawei machine trial exercise questions] 45. Calculate the number of 1 in a binary number.

Source: Internet
Author: User

[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.

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.