UVa 343 - What Base Is This?

来源:互联网 发布:不醉不会 田馥甄 知乎 编辑:程序博客网 时间:2024/05/17 03:58

题目:已知两个数字串,问他们分别是多少进制时相等。

分析:简单题。直接枚举每个数字的不同进制(最大的数字+1 ~ 36),转换成10进制判断相等即可。

说明:数值转换到10进制时数字不超过整形范围。

#include <algorithm>#include <iostream>#include <cstdlib>#include <cstring>#include <cstdio>#include <cmath>using namespace std;//计算字符数值 int ValueChar(char ch){if (ch >= '0' && ch <= '9')return ch-'0';return ch-'A'+10;}//计算字符串数值 int ValueStr(int base, char buf[]){int value = 0;for (int i = 0; buf[i]; ++ i) {value *= base;value += ValueChar(buf[i]);}return value;}int main(){char str1[101],str2[101];while (~scanf("%s%s",str1,str2)) {//找到每个串的最小进制 int max1 = 1,max2 = 1;for (int i = 0; str1[i]; ++ i)if (max1 < ValueChar(str1[i]))max1 = ValueChar(str1[i]);for (int i = 0; str2[i]; ++ i)if (max2 < ValueChar(str2[i]))max2 = ValueChar(str2[i]);//查找不同的进制时相同的值 int flag = 0;for (int i = max1+1; i < 37; ++ i)for (int j = max2+1; j < 37; ++ j)if (!flag && ValueStr(i, str1) == ValueStr(j, str2)) {flag = 1;printf("%s (base %d) = %s (base %d)\n",str1,i,str2,j);}if (!flag)printf("%s is not equal to %s in any base 2..36\n",str1,str2);}    return 0;}


0 0