院校机试刷题第五天:1912循环位移、1913礼炮车
一、1912循环位移
1.题目描述
2.解题思路
一道模拟题,首先要判断长度是否一致,排除掉长度不相同的情况。
在一个字符串中找到另一个字符串的开头,然后依次遍历比对,用队列也不会方便多少,直接下标索引比对即可。
3.代码
#include <iostream>
#include <string>
using namespace std;bool judge(string str1, string str2) {int length1 = str1.length();int length2 = str2.length();if(length1 != length2) {return false;}// 在str1中循环找str2int start = str2[0];int start_index = str1.find(start);int index = start_index; // 用于在循环中遍历str2int i = 0;while(length2--){if(index >= length1) {index -= length1;}if(str2[i] != str1[index]) {return false;}i++;index++;}return true;
}int main() {string str1, str2;cin >> str1 >> str2;bool result = judge(str1, str2);if(result == true) {cout << 'Y';} else {cout << 'N';}return 0;
}
二、1913礼炮车
1.题目描述
2.解题思路
这个题没给输入输出就很逆天
这也是一道模拟题,类似小学数学吧,可以手算写上去。
其实就是求解5 6 7 的最小公倍数,先求56的,再求57的,再求67的,再求567的,然后除去公共的,减一下。其实这样不如找到最大的那个数字,然后按数字一个一个遍历能否被5 6 7整除,如果可以就count++,最后输出count。
3.代码
#include <iostream>
using namespace std;int num(int a, int b, int c, int total) {// 第0秒一定三个统一放一次,此时还需要放的炮只剩下total-1int count1 = 1;int maxlength = c * (total - 1);for(int i = 1; i <= maxlength; i++) {// 除了要检查能否被间隔时间整除,还要检查是否在该车的发射时间内if((i % a == 0) && (i <= a * (total - 1)) ||(i % b == 0) && (i <= b * (total - 1)) ||(i % c == 0) && (i <= c * (total - 1))) {count1++;}}return count1;
}int main() {int a = 5, b = 6, c = 7, total = 21;int count1 = num(a, b , c, total);cout << count1;return 0;
}