方法一
判断该数字是否大于0,若大于0,则模2取余,判断余数是否为1,然后将该数除以2。
不断循环该过程。直至该数为0。
代码
#include<bits/stdc++.h>
using namespace std;
int f(int n){
int count = 0; //统计1的个数
if(n == 0)
return 0;
else{
while(n > 0){
if(n % 2 == 1){
count++;
}
n /= 2;
//或者n >>= 1;
}
}
return count;
}
int main(){
int n;
cin >> n;
cout << "1的个数:" << f(n);
return 0;
}
方法二
将该数字 &1 ,若结果为1,则统计1的个数加1。否则继续&,直到该数为0。
#include<bits/stdc++.h>
using namespace std;
int f(int n){
int count = 0; //统计1的个数
if(n == 0)
return 0;
else{
while(n > 0){
if(n&1 == 1)
count++;
n >>= 1;
}
}
return count;
}
int main(){
int n;
cin >> n;
cout << "1的个数:" << f(n);
}
方法三(最高效)
将数字 n 与数字 n-1 进行&运算,运算一次,统计一次。
循环该过程,直至数字为0。
#include<bits/stdc++.h>
using namespace std;
int f(int n){
int count = 0; //统计1的个数
if(n == 0)
return 0;
else{
while(n > 0){
n = n&(n - 1);
count++;
}
}
return count;
}
int main(){
int n;
cin >> n;
cout << "1的个数:" << f(n);
}