题目
分析
- 将输入的数字看作字符串,然后将字符串转成真实值
- 计算两个真实值,然后从1开始遍历公约数,每次发现一个更大的公约数就替换,直到找不到公约数
代码
#include <cstdio>
#include <map>
#include <string>
#include <cmath>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;long long str2num(char *num,int length){long long sum = 0;for(int i=0;i<length;i++){long long temp = num[i]-'0';for(int j=0;j<length-i-1;j++){temp *= 10;}sum += temp;}return sum;
}long long find_max(long long n1,long long n2){long long max = 1;for(long long i=2;i<=n1&&i<=n2;i++){if(n1%i==0&&n2%i==0){if(i>max){max = i;}}}return max;
}int main(){char num1[100];char num2[100];while(scanf("%s%s",num1,num2)!=EOF){string num_1 = num1;string num_2 = num2;for(int i=0;i<num_1.length()/2;i++){char temp = num1[i];num1[i]=num1[num_1.length()-1-i];num1[num_1.length()-1-i]=temp;}for(int i=0;i<num_2.length()/2;i++){char temp = num2[i];num2[i]=num2[num_2.length()-1-i];num2[num_2.length()-1-i]=temp;}long long n_1 = str2num(num1,num_1.length());long long n_2 = str2num(num2,num_2.length());printf("%lld\n",find_max(n_1,n_2));}return 0;
}
例题——循环位移
分析
- 输入是字符串,首先判断两个字符串长度相等吗,不相等直接返回N
- 如果相等,那么判断字符串是不是由另一个字符串循环移位得来的,我们只需要判断两个字符串相等的元素序号是不是相差相等的值,参照循环队列,需要注意的是,当某一个序号超过字符串长度时,需要对长度取余
代码
#include <cstdio>
#include <map>
#include <string>
#include <cmath>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;
char can_it(char *str1,char *str2, int length){for(int i=0;i<length;i++){if(str1[0]!=str2[i]){continue;}bool flag = true;for(int j=1;j<length;j++){if(str1[j]!=str2[(i+j)%length]){flag=false;break;}}if(flag == false){continue;}else{return 'Y';}}return 'N';
}int main(){char num1[100];char num2[100];while(scanf("%s%s",num1,num2)!=EOF){string num_1 = num1;string num_2 = num2;if(num_1.length()!=num_2.length()){printf("N\n");}else{printf("%c\n",can_it(num1,num2,num_1.length()));}}return 0;
}