二进制运算
Description
若将一个正整数化为二进制数,在此二进制数中,我们将数字1的个数多于数字0的个数的这类二进制数称为A类数,否则就称其为B类数。
例如:
(13)_{10} =(1101)_2
其中1的个数为3,0的个数为1,则称此数为A类数;
(10)_{10} =(1010)_2
其中1的个数为2,0的个数也为2,称此数为B类数;
(24)_{10} =(11000)_2
其中1的个数为2,0的个数为3,则称此数为B类数;
程序要求:
求出1~n之中(包括1与n),全部A、B两类数的个数。(其中n<=1000)
Input
输入一行一个数n
Output
在一行中输出两个整数A和B,A表示A类数的个数,B表示B类数的个数,AB之间由一个空格分隔,除此之外不要再输出其他多余的东西。
Sample Input 1
1000
Sample Output 1
538 462
YCOJ:NOIP1995
提示:借助十进制转二进制的方法,在程序里进行累加,将零和一分别统计,再将统计的数比较累加。
是的,这道题很坑,比较零和一都要取数,(不说了( ̄▽ ̄)~*)。
对于二进制数,我们先来看看这个代码:
#include <bits/stdc++.h>
using namespace std;
int a[10010];
int main(){
int n;
cin>>n;
int k=0;
while(n!=0){
a[k]=n%2;//求余数
n/=2;//求他的位数
k++;
}
for(int i=k-1;i>=0;i--){//倒序输出(转二进制的方法自己去看,不关我事罒ω罒)
cout<<a[i];
}
return 0;
}
相信大家都理解了,(不理解百度)。
解析:按照去二进制的方法,将for循环从1——n来限制范围,为了避免超时,就要将i的值统计一下,最后来判断如果1比0多就++,否则再++,最后将统计的数拿来比较,统计出个数。
AC代码:
#include <bits/stdc++.h>
using namespace std;
int a[10010];
int main(){
int n;
cin>>n;
int sum=0,ans=0;
for(int i=1;i<=n;i++){
int cnt=0,tot=0;
int asd=i;
while(asd!=0){
int sdf=asd%2;//除余数
if(sdf==1){
cnt++;
}else if(sdf==0){
tot++;
}
asd/=2;
}
if(cnt>tot){
sum++;
}else{
ans++;
}
}
cout<<sum<<" "<<ans;
return 0;
}
然后就简单了 。