【深基6.例2】小书童——凯撒密码 · 教师题解

【深基6.例2】小书童——凯撒密码

解题思路

每个字母转为 0~25 的序号,加偏移 n 后模 26,再加回 a。

正确性说明

字母表构成长度 26 的环,取模恰好实现越过 z 后从 a 继续的循环移动。

易错点

加偏移后再取模;偏移为 26 时保持原字母。

复杂度

时间 O(L),空间 O(L)。

参考代码(C++11)

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    string s;
    cin >> n >> s;
    for (char &c : s)
        c = char((c - 'a' + n) % 26 + 'a');
    cout << s << "\n";
    return 0;
}
返回题目