唐磊的个人博客

pat1010—Radix

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


这个题目,参考了网上其他人的解法。

include <stdio.h>
#include <string.h>
long num2Dec(char *,int);//转换成10进制数据
long findLowRadix(char *);//寻找最低进制数
long binarysearch(char *,long ,long, long);
int main()
{
char N1[11],N2[11];
int tag,radix;
long target = 0L,result=0L;
long least;//进制最小
long most;//进制最大
scanf("%s%s",N1,N2);
scanf("%d%d",&tag,&radix);
if(1 == tag)
{
target = num2Dec(N1,radix);
least=findLowRadix(N2);
most = (target + 1 > least + 1) ? target +1 :least +1;
result = binarysearch(N2,least,most,target);
if(result == -1)
printf("Impossible");
else
printf("%d\n",result);
}else if(2 == tag)
{
target = num2Dec(N2,radix);
least=findLowRadix(N1);
most = (target + 1 > least + 1) ? target +1 :least +1;
result = binarysearch(N1,least,most,target);
if(result == -1)
printf("Impossible");
else
printf("%d\n",result);
}
return 0;
}
long num2Dec(char *p,int radix)
{
int len = strlen(p);
int m=1,num=1,sum=0;
int i=0;
for(i=len-1;i>=0;i--)
{
if(p[i]>='a' && p[i]<='z')
num = p[i]-'a' + 10;
else if(p[i] >= '0' && p[i] <= '9')
num = p[i]-'0';
sum += num*m;
m*=radix;
}
return sum;
}
//ab:最小就是12进制 69:最小就是10进制
long findLowRadix(char *p)
{
long len=strlen(p),low=0,num=0,i=0;
for(i=len-1;i>=0;i--)
{
if(p[i]>='a'&&p[i]<='z')
num= p[i] - 'a' + 10;
else if(p[i]>='0'&& p[i]<='9')
num=p[i] - '0';
if(num+1>low)
low=num+1;
}
return low;
}
long binarysearch(char *p,long low,long high,long target)
{
long mid=low,tmp=0;
while(low<=high)
{
tmp = num2Dec(p,mid);
if(tmp > target)
high=mid-1;
else if(tmp < target)
low = mid+1;
else
return low;
mid = (low+high)/2;
}
return -1;
}
tanglei wechat
欢迎扫描二维码关注我的微信公众号