1 条题解

  • 0
    @ 2067-5-28 8:11:46

    【深基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;
    }
    
    • 1

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

    信息

    ID
    101
    时间
    1000ms
    内存
    512MiB
    难度
    进阶
    标签
    递交数
    1
    已通过
    1
    上传者