My洛谷题解_P1914 小书童——凯撒密码

  原题目:

 

  这个题目其实很简单,但是有两个主要的坑:

  1.题目给出的n可能是大于26的。比如我向后移动1位和移动27位实际上的效果是一样的,所以需要我们先对n模26得到实际移动的位数。

  2.小写英文字母的ASCII码最大为'z'等于122,而char类型的最大值为127。使用字符数组时若直接加n可能会使数组元素溢出,而数组元素一旦溢出,其数值就会变为相应的负数,运行结果就会出错。有一种解决方法是先将数组元素减去'a',操作之后再加上'a',就可以有效避免溢出问题。

  代码如下

  

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 void fun(int n) {
 6 
 7     string str;
 8     cin >> str;
 9     
10     //实际的偏移量为n模26
11     int t = n % 26;
12 
13     //令len等于数组的大小,这样可以避免之后的循环中频繁调用size()函数
14     int len = str.size();
15 
16     for (int i = 0; i < len; i++) {
17         str[i] = (str[i] - 'a' + t) % 26 + 'a';
18         cout << str[i];//可以在上方直接输出计算后的str[i]值,无需对原数组进行修改
19     }
20 }
21 
22 int main() {
23 
24     int n;
25     cin >> n;
26     fun(n);
27 
28     return 0;
29 }

 

posted @ 2021-02-04 17:03  亦是不凡  阅读(228)  评论(0编辑  收藏  举报