假设A=1,B=2,以此类推;a=27,b=28以此类推;空格=0。对于输入的字符串,加密的结果就是字符串每一位对应的数值乘以这一位下标之和,下标从1开始。比如ACEe加密的过程如下:
ACEeA加密为:1×1 + 2×3 + 3×5 + 4×31 + 5×1= 151
Input Format
一行字符串,保证只包含大小写字母和空格。字符串长度不超过1000,并且首位和末位不是空格。
Output Format
一个数字,表示加密结果。
for循环。思路在于ASCII码值的使用,还有字符串下标的利用。上代码,楼主收代码。
#include<iostream>
using namespace std;
int main()
{
char str[1005];
while(gets(str))
{
int res = 0;//加密结果置0
for(int i=0;str[i];i++)
{
if(str[i]>='A'&&str[i]<='Z') //字符在A-Z中
{
res += (str[i]-'A'+1)*(i+1); //(字符下标+1)* 字母值
}
else if(str[i]>='a'&&str[i]<='z')//字符在a-z中,
{
res += (str[i]-'a'+27)*(i+1); //(字符下标+1)* 字母值
}
else if(str[i]==' ')
{
//等于空格不处理
}
else
{
cout<<"输入了非法字符"<<endl;
}
}
cout<<res<<endl;
}
return 0;
}
来个 C++11
风格的:
#include <algorithm>
#include <cassert>
#include <string>
#include <iostream>
int encrypt(const std::string& content) {
auto i = 1;
return std::accumulate(content.begin(), content.end(), 0, [&](const int& a, char b) {
char c;
if (b >= 'A' && b <= 'Z')
c = b - 'A' + 1;
else if (b >= 'a' && b <= 'z')
c = b - 'a' + 26 + 1;
else if (b == ' ')
c = 0;
else
assert(false);
return a + c * i++;
});
}
int main()
{
std::string s("ACEeA");
std::cout << "encrypt ret: " << encrypt(s) << std::endl;
}