140人阅读 评论(0)

400 ms

65536 kB

16000 B

Standard

CHEN, Yue

Given a pair of positive integers, for example, 6 and 110, can this equation 6 = 110 be true? The answer is "yes", if 6 is a decimal number and 110 is a binary number.

Now for any pair of positive integers N1 and N2, your task is to find the radix of one number while that of the other is given.

Input Specification:

Each input file contains one test case. Each case occupies a line which contains 4 positive integers:
Here N1 and N2 each has no more than 10 digits. A digit is less than its radix and is chosen from the set {0-9, a-z} where 0-9 represent the decimal numbers 0-9, and a-z represent the decimal numbers 10-35. The last number "radix" is the radix of N1 if "tag" is 1, or of N2 if "tag" is 2.

Output Specification:

For each test case, print in one line the radix of the other number so that the equation N1 = N2 is true. If the equation is impossible, print "Impossible". If the solution is not unique, output the smallest possible radix.

Sample Input 1:
6 110 1 10

Sample Output 1:
2

Sample Input 2:
1 ab 1 2

Sample Output 2:

Impossible

//题目思路：

//1、首先将输出数据用字符串接收，接收后计算它所有进制中最小的进制数；
//2、从最小进制数开始到最大进制，依次转换该数为十进制
//3、专门写一个函数实现任意进制的数向十进制数的转换
//4、将两数都转化为十进制数进行比较
//
//测试点总结：
//2、进行十进制转化时，要注意字母的特殊处理
//3、注意进制的遍历，要挨个查找，不是直接去最小的进制哦

{
for (int i = 0; i < n.length(); i++)
{
char c = n[i];
int num = 0;
if (isalpha(c))//判断是否为字母
{
num = c - 87;
}
else
{
num = c - '0';
}
{
}
}
}

long int ChangtoDecimal(string n, int r)//分别表示该数和该数对应的进制
{
long int sum = 0;
int len = n.length();
for (int i = len - 1; i >= 0; i--)
{
//要注意处理字符串中为字母的情况
char c = n[i];
int bnum = 0;
if (isalpha(c))
{
bnum = c - 87;
}
else
{
bnum = c - '0';
}
sum += bnum*pow(r,len-1-i);
}
return sum;
}

int main()
{
string n1, n2;
int r1, r2;//分别记录两个数的进制
if (tag == 1)
{

int flag = 0;
long int num1 = ChangtoDecimal(n1, r1);//其实这个数有可能很大，long int也是一个测试点
for (long int r = r2; r <= MAX_radix; r++)
{
//将两个数都转化为十进制数进行比较
long int num2 = ChangtoDecimal(n2, r);//一开始没想清楚，应该是任意进制都要进行比较
if (num1 == num2)
{
cout << r;
flag = 1;
break;
}
}
if (flag == 0)
{
cout << "Impossible";
}
}
else if (tag==2)
{
//将两个数都转化为十进制数进行比较
int flag = 0;
long int num2 = ChangtoDecimal(n2, r2);
for (long int r = r1; r <= MAX_radix; r++)
{
//将两个数都转化为十进制数进行比较
long int num1 = ChangtoDecimal(n1, r);
if (num1 == num2)
{
cout << r;
flag = 1;
break;
}
}
if (flag == 0)
{
cout << "Impossible";
}
}
return 0;
}
【参考】最后的调试，我参考这个人写的分析报告，感觉写的不错http://www.cnblogs.com/549294286/p/3571604.html

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：53106次
• 积分：1394
• 等级：
• 排名：千里之外
• 原创：77篇
• 转载：84篇
• 译文：0篇
• 评论：4条
阅读排行
最新评论