A1010 Radix (25 point(s))

进制转换

1. 原文

原题

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:

1
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:

1
6 110 1 10

Sample output 1:

1
2

Sample Input 2:

1
1 ab 1 2

Sample output 2:

1
Impossible

2. 解析

取 [数值+1,最大数位+1] 二分法求得结果

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include<cstdio>
#include<cstring>
#include<cctype>
char str1[20],str2[20];
long long getNum(char str[],long long radix){
long long num = 0l;
int len = strlen(str);
long long p = 1l;
for (int i = len-1; i>=0; i--)
{
if(isdigit(str[i])){
num += (str[i]-'0')*p;
}else{
num += (str[i]-'a'+10)*p;
}
p*=radix;
}
return num;
}
long long getIndex(char str[]){
long long num = -1;
for (int i = 0; str[i] != '\0'; ++i)
{
long long temp = 0;
if (isdigit(str[i]))
{
temp = str[i]-'0';
}else{
temp = str[i]-'a'+10;
}
if (temp>num)
{
num = temp;
}
}
return num;
}
void getAns(char s1[],char s2[],long long radix){
long long num = getNum(s1,radix);
long long left = getIndex(s2)+1;
long long right = num+1;
int flag = 0;
while(left<=right){
long long mid = (left+right)/2;
long long ans = getNum(s2,mid);
if (ans==num)
{
flag = 1;
printf("%lld\n",mid);
break;
}else if(ans>num||ans<0){
right = mid - 1;
}else{
left = mid+1;
}
}
if (flag == 0)
{
printf("Impossible\n");
}
}
int main(){
int tag;
long long radix;
scanf("%s%s%d%lld",str1,str2,&tag,&radix);
if (tag == 1)
{
getAns(str1,str2,radix);

}else{
getAns(str2,str1,radix);
}


return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1010/
  • 发布时间: 2019-09-03 12:36
  • 更新时间: 2021-10-29 13:58
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!