1 条题解

  • 0
    @ 2025-4-19 16:29:54

    思路: 题目大意: 对消息原文中的每个字母,分别用该字母之后的第5个字母替换(例如:消息原文中的每个字母A都分别替换成字母F),其他字符不 变,并且消息原文的所有字母都是大写的 给定翻译后的消息,求原始信息 题解: 注意一个坑就好了,一样是循环,比如X可以变成C,

    题目分析

    本题要求对凯撒加密的消息进行解密。凯撒加密是将每个字母替换为其后第 5 个字母,解密则是将加密后的字母转换回原始字母。消息中只有字母会发生替换,非字母字符保持不变,且消息原文的字母均为大写。输入包含多个数据集,每个数据集由起始行“START”、加密消息行、结束行“END”组成,最后以“ENDOFINPUT”表示输入结束。

    解题思路

    1. 读取输入的字符串,当遇到“START”和“END”时跳过,因为它们只是用于标识数据集的开始和结束。
    2. 当遇到“ENDOFINPUT”时,结束程序。
    3. 对于加密消息字符串,遍历其中每个字符:
      • 如果字符是大写字母(即 Code_str[index] <= 'Z' && Code_str[index] >= 'A'),进行解密操作。
        • 如果该字母减去 5 后小于 'A',则通过 Code_str[index] = 'Z' - (4 - (Code_str[index] - 'A')) 计算出对应的原始字母。
        • 否则,直接将该字母减去 5 得到原始字母。
      • 如果字符不是大写字母(即非字母字符),保持不变。
    4. 将解密后的字符输出,每个数据集的解密结果占一行。
    #include<iostream>
    #include<string>
    #include<vector> // Included vector header, although not used in this snippet
    using namespace std;
    
    string Start = "START";
    string End = "END";
    string End_input = "ENDOFINPUT";
    
    int main()
    {
    	string Code_str;
    	while (getline(cin,Code_str))
    	{
    		if (Code_str == Start || Code_str == End) //跳过提示字符串
    			continue;
    		if (Code_str == End_input)
    			break;
    
    		// Fix the warning by using size_t for the index
    		size_t index = 0;
    		while (index != Code_str.length())
    		{
    			if (Code_str[index] <= 'Z' && Code_str[index] >= 'A')
    			{
    				// Ensure calculations also handle wrapping correctly
    				// 'A' to 'Z' are consecutive ASCII values
    				// char arithmetic might behave differently for negative results
    				// It's safer to work with the position (0-25)
    				int char_pos = Code_str[index] - 'A';
    				char_pos = (char_pos - 5 + 26) % 26; // Subtract 5, add 26 to handle negative results before modulo
    				Code_str[index] = char_pos + 'A';
    
                    // Original logic (Code_str[index] - 5 < 'A') is also okay
                    // if char arithmetic is guaranteed to wrap/handle negative correctly
                    // on your platform, but working with 0-25 range is more portable.
                    /* Original logic re-written for clarity:
    				if (Code_str[index] < 'F') // If char is A, B, C, D, E
    					Code_str[index] = 'Z' - ('E' - Code_str[index]); // Z - (pos_of_E - pos_of_char)
                                                                     // 'Z' - (('E'-'A') - (char-'A')) = 'Z' - (4 - (char-'A'))
    				else
    					Code_str[index] -= 5;
                    */
    
    			}
    			cout << Code_str[index];
    			index++;
    		}
    		cout << endl;
    		Code_str.clear();
    
    	}
    	return 0;
    }
    • 1

    信息

    ID
    299
    时间
    1000ms
    内存
    256MiB
    难度
    10
    标签
    递交数
    9
    已通过
    1
    上传者