题目:
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:
N1 N2 tag radix
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
解析:
本题拿到23分。测试7超时,测试10错误。没想明白错哪了。烦请大佬指正。
输入:两个数字,一个标记符,一个进制。
标记符为1,则进制代表第一个数的进制;为2则代表第二个数的进制。
输出使两个数字相等的最小进制。如果没有就输出不可能。
思路是根据各位的最大数字求出最小进制,将两个数字的十进制结果比较。进制逐渐增加直到相等(输出进制)或者超出(输出不可能)。
答案:
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int search(string str)//根据最大的字符,求出最小的可能进制
{
int radix=0;
for(int i=0;i<str.length();i++)
{
int temp;
if(str[i]>='0'&&str[i]<='9')
{
temp=str[i]-'0';
}
else
{
temp=str[i]-'a'+10;
}
if(temp>radix)
{
radix=temp;
}
}
radix++;
//即最大字符为x时,进制最小为x+1
return radix;
}
int trans(string str,int radix)
{
int sum=0;
for(int i=0;i<str.length();i++)
{
if(str[i]>='0'&&str[i]<='9')
{
sum=sum*radix+str[i]-'0';
}
else
{
sum=sum*radix+str[i]-'a'+10;
}
}
return sum;
}
int main()
{
string left,right;//输入的数字用字符串存储
int leftnum,rightnum;
int flag,radix,result;
cin>>left>>right>>flag>>radix;
flag--;
if(flag)//已给出右侧进制
{
swap(left,right);
}
leftnum=trans(left,radix);//计算左侧输入的十进制值
result=search(right);//计算右侧输入的最小进制
rightnum=trans(right,result);
while(rightnum<leftnum)
{
result++;
rightnum=trans(right,result);
}
if(rightnum==leftnum)
{
cout<<result;
}
else
{
cout<<"Impossible";
}
}