1.统计字符串中1的个数
输入:010101
输出:3
代码:
#include <iostream>
#include <string>
using namespace std;
int main(){
string str;
cin >> str;
int count = 0;
//用迭代器遍历字符串
for(string::iterator it = str.begin(); it != str.end(); it++){
if(*it == '1'){
count++;
}
}
cout << count << endl;
return 0;
}
2.统计二进制中1的个数
解题思路:将二进制数按位相与,若为1,计数器++,否则该二进制数按位右移
#include <iostream>
#include <cmath>
using namespace std;
//输入一个数,转为二进制,统计二进制中1的个数
class Solution{
public:
//将整数转为二进制
十进制转为二进制,先取余,再除以2,再把结果累加
void erJinZhi(int n){
int b, bin = 0;
int i = 0;
while(n!=0){
b = n%2;
n /= 2;
bin = bin + b*pow(10, i);
i++;
}
cout << "整数"<< n << "的二进制数是:" << bin << endl;
}
//统计该数的二进制中有几个1
//思想:按位相与
int coutOne(int n){
int count = 0, i = 32; //设置32位二进制数
while(i--){
if(n & 1){ //按位相与
count++;
}
n = n>>1;
}
cout << count << endl;
return count;
}
};
int main(){
int n;
cin >> n;
Solution s;
s.erJinZhi(n);
s.coutOne(n);
return 0;
}