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)