PAT(甲级)1010. Radix (25)
2018-01-20 20:58
555 查看
Radix (25)
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
题目大意:给出两个数字串 与 其中一个的进制 若tag==1则给出的为第一个数的进制 tag==2为第二个数的进制 现在求一个进制使两个数字串的值相等
分析:首先想到讲所给进制的数转换为10进制,然后将另一个串转换进制,一直与第一个数比较 相等则输出进制,大于输出Impossible 小于则增加进制再比较 提交24分 一个测试点超时 后来想到进制可能超int很大 遍历增加超时 只能用二分 但是没想到二分的上限 百度一下才明白 还有就是处理溢出问题 之前遍历增加不存在此问题 二分则会有这个问题 因为进制很大很大
#include <iostream> #include<cstdio> #include<cmath> #include<cstring> using namespace std; char s1[12],s2[12]; long long trans(char s[12],long long r){ long long n=0; int lens=strlen(s); for(int i=lens-1;i>=0;i--){ if(s[i]>'9'){ n+=pow(r,lens-1-i)*(s[i]-'a'+10); } else n+=pow(r,lens-1-i)*(s[i]-'0'); if(n<0)//溢出 return -1; } return n; } int main() { int tag,flag; long long n1,n2,rd; long long l,r,m; scanf("%s%s",s1,s2); scanf("%d%lld",&tag,&rd); if(tag==1) n1=trans(s1,rd); else{ n1=trans(s2,rd); memset(s2,'\0',sizeof(s2)); strcpy(s2,s1); } l=0; int lens=strlen(s2); for(int i=0;i<lens;++i){ if(s2[i]>'9'){ if(s2[i]-'a'+10>l) l=s2[i]-'a'+10; } else if(s2[i]-'0'>l) l=s2[i]-'0'; } l++;//进制下限 r=n1+1;//进制上限 防止 35 z 1 10 这种数据 flag=0; while(l<=r){ m=(l+r)/2; n2=trans(s2,m); if(n2==n1){ flag=1; break; } else if(n2<0||n2>n1)//溢出肯定是大于n1 r=m-1; else l=m+1; } if(flag) printf("%lld",m); else printf("Impossible"); return 0; }
相关文章推荐
- PAT甲级-1010. Radix (25)进制
- 1010. Radix (25) PAT 甲级
- 1010. Radix (25)-PAT甲级真题(二分法)
- PAT甲级 1010.Radix(25) 题目翻译与答案
- PAT甲级1010. Radix (25)
- [PAT甲级]1010. Radix (25)(求另一个数的基数)
- PAT-甲级-1010 Radix(25)
- 【PAT甲级】1010. Radix (25)
- PAT甲级 1010. Radix (25)
- pat甲级1010. Radix (25)
- PAT甲级1010 . Radix (25)
- pat 甲级 1010. Radix (25)
- PAT 甲级 1010. Radix (25)
- PAT 甲级 1010.Radix (25)
- pat甲级1010. Radix (25)
- PAT-1010 Radix (25)
- 【PAT】1010. Radix (25)
- PAT 1010. Radix(25)
- PAT_A 1010. Radix (25)
- PAT-A 1010. Radix (25)