"C" Enter an integer that outputs the number of 1 in the binary representation (three methods)

Source: Internet
Author: User

Enter an integer that outputs the number of 1 in the binary representation. such as input 32, output 1.


Code implementation:


Method 1: and operation

#define _crt_secure_no_warnings 1#include<iostream>using namespace Std;int findonenumber (unsigned int num) {int n    Umberofone = 0;        while (num) {num = num & (num-1);    numberofone++; } return numberofone;}    void Test () {int num = 32; Cout<<findonenumber (num) <<endl;}    int main () {Test ();    System ("pause"); return 0;}


Method 2: modulo Division

#define _crt_secure_no_warnings 1#include<iostream>using namespace Std;int findonenumber (unsigned int num) {int n    Umberofone = 0;        while (num) {if (num% 2 = = 1) numberofone++;    Num/= 2; } return numberofone;}    void Test () {int num = 32; cout << findonenumber (num) << Endl;}    int main () {Test ();    System ("pause"); return 0;}


Method 3: shift

#define _crt_secure_no_warnings 1#include<iostream>using namespace Std;int findonenumber (unsigned int num) {int n    Umberofone = 0;        while (num) {if (num & 1) numberofone++;    num = num >> 1; } return numberofone;}    void Test () {int num = 32; cout << findonenumber (num) << Endl;}    int main () {Test ();    System ("pause"); return 0;}


This article is from "Han Jing's Blog", please make sure to keep this source http://10740184.blog.51cto.com/10730184/1771992

"C" Enter an integer that outputs the number of 1 in the binary representation (three methods)

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.