L1-058 6翻了 (15 分)
“666”是一种网络用语,大概是表示某人很厉害、我们很佩服的意思。最近又衍生出另一个数字“9”,意思是“6翻了”,实在太厉害的意思。如果你以为这就是厉害的最高境界,那就错啦 —— 目前的最高境界是数字“27”,因为这是 3 个 “9”!
本题就请你编写程序,将那些过时的、只会用一连串“6666……6”表达仰慕的句子,翻译成最新的高级表达。
输入格式:
输入在一行中给出一句话,即一个非空字符串,由不超过 1000 个英文字母、数字和空格组成,以回车结束。
输出格式:
从左到右扫描输入的句子:如果句子中有超过 3 个连续的 6,则将这串连续的 6 替换成 9;但如果有超过 9 个连续的 6,则将这串连续的 6 替换成 27。其他内容不受影响,原样输出。
输入样例:
it is so 666 really 6666 what else can I say 6666666666
输出样例:
it is so 666 really 9 what else can I say 27
先看我之前的代码吧,没拿全分,15分的题只拿了12分,想了很久才发现一个漏洞
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
string str;
getline(cin,str);
int count = 0;
for(int i = 0; i < str.length(); i++)
{
if (str[i] == '6')//没有考虑到最后一个字符是6的情况,如果最后一个字符为6
//且个数不大于3,最后6就输不出来了
{
count++;
if (count>9)
{
cout<<"27";
}
else if (count > 3&&str[i+1] == ' ')
{
cout<<"9";
}
}
else if (str[i] != '6')
{
if (count>0&&count<4)
{
for (int j = 0; j<count; j++)
{
cout<<"6";
}
}
count = 0;
cout<<str[i];
}
}
getchar();
return 0;
}
上面这段代码还会出现一个warning
a.cpp: In function ‘int main()’:
a.cpp:9:19: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for(int i = 0; i < str.length(); i++)
signed 和unsigned数据的范围不同,警告可能出现一个很大的数据,
所以将这一句改为for(std::size_t i = 0; i < str.size(); i++)就不会出现警告了
size_t 类型定义在cstddef头文件中
#include<iostream>
#include<cstring>
#include<stddef.h>
using namespace std;
int main()
{
string str;
getline(cin,str);
int count = 0;
for(std::size_t i = 0; i < str.size(); i++)
{
if (str[i] == '6')
{
count++;
if (i != str.length()-1)continue;
//考虑最后一个字符是6的情况,处理时直接结束本次循环,进入到特殊情况处理
}
else if (str[i] != '6')
{
if (count>9)
{
cout<<"27";
}
else if (count > 3)
{
cout<<"9";
}
else if (count < 4)
{
for (int j = 0; j<count; j++)
{
cout<<"6";
}
}
count = 0;
cout<<str[i];
}
//特殊情况处理
//最后一个字符是6的情况,处理方法:
if (count > 9)
cout<<"27";
else if (count > 3)
cout<<"9";
else
for (int j = 0; j<count; j++)
{
cout<<"6";
}
}
getchar();
return 0;
}