题目https://www.patest.cn/contests/pat-b-practise/1057
遇到的问题:
1.求字符串长度,因为我最开始用的是string,所以选择string.size(),但是由于cin函数的问题,我改为了gets(),所以字符串也用字符数组替换,用了strlen()函数,头文件为string.h;
输入函数http://www.cnblogs.com/flatfoosie/archive/2010/12/22/1914055.html
2.记录二进制的0,1问题
while(sum != 0)
{
int res = sum % 2;
if(res == 0)
countZero ++;
else
countOne ++;
sum = sum / 2;
}
我还看到了一个方法
#include<iostream>
using namespace std;
void printbinary(const unsigned int val)
{
for(int i = 16; i >= 0; i--)
{
if(val & (1 << i))
cout << "1";
else
cout << "0";
}
}
int main()
{
printbinary(1024);
return 0;
}
3.其他进制转换
http://blog.csdn.net/xiaofei2010/article/details/7434737
题目代码
#include<iostream>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
char str[100002];
using namespace std;
int main()
{
gets(str);
int sum=0;
for(int i=0;i<=strlen(str);i++)
{
if(str[i]>='a'&&str[i]<='z')
{
sum+=str[i]-'a'+1;
}
if(str[i]>='A'&&str[i]<='Z')
{
sum+=str[i]-'A'+1;
}
}
int countZero=0,countOne=0;
while(sum != 0)
{
int res = sum % 2;
if(res == 0)
countZero ++;
else
countOne ++;
sum = sum / 2;
}
cout<<countZero<<" "<<countOne;
return 0;
}