博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PAT甲级——A1010 Radix
阅读量:4542 次
发布时间:2019-06-08

本文共 2603 字,大约阅读时间需要 8 分钟。

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 这题不难,主要是要考虑数据溢出的问题,和使用二分法去寻找匹配的二进制,而二分法中的左右边界是要考虑怎么得到的,这是个难点
1 #include 
2 #include
3 #include
4 #include
5 #include
6 using namespace std; 7 8 //最简单的一种一种格式试 9 int main()10 {11 string N1, N2;12 long long int tag,radix;//防止溢出13 cin >> N1 >> N2 >> tag >> radix;14 if (tag == 2)15 {16 string N = N2;17 N2 = N1;18 N1 = N;19 }20 long long int aim = 0, n = 0;//防止化为10制止时溢出21 for (int i = N1.length() - 1, j = 0; i >= 0; ++j, --i)//将N1划为10进制22 {23 n = isdigit(N1[i]) ? (N1[i] - '0') : (N1[i] - 'a' + 10);24 aim += n * pow(radix, j);25 }26 long long int l, r, m;27 char it = *max_element(N2.begin(), N2.end());//找出最大的元素28 l = (isdigit(it) ? it - '0' : it - 'a' + 10) + 1;//找到N2形成的最小进制 29 r = max(aim, l);30 while (l <= r)31 {32 m = l + (r - l) / 2;33 long long int res = 0, n;34 for (int i = N2.length() - 1, j = 0; i >= 0; ++j, --i)35 {36 n = isdigit(N2[i]) ? (N2[i] - '0') : (N2[i] - 'a' + 10); 37 res += n * pow(m, j);38 }39 if (res == aim)40 break;41 else if (res<0 || res>aim)42 r = m - 1;43 else44 l = m + 1;45 }46 if (l > r)47 cout << "Impossible" << endl;48 else49 cout << m << endl;50 51 return 0;52 53 }

 

转载于:https://www.cnblogs.com/zzw1024/p/11178506.html

你可能感兴趣的文章
PHP 基础
查看>>
Pile 0002:重入代码
查看>>
Edge Code CC卡死原因
查看>>
今天编译遇到的问题
查看>>
人,绩效和职业道德读后感
查看>>
BZOJ 3132(上帝造题的七分钟-树状数组求和+2D逆求和数组)
查看>>
第二次作业——结对项目之需求分析与原型模型设计 (暂记。未完成。。)
查看>>
Docker安装
查看>>
20145221 《Java程序设计》第九周学习总结
查看>>
小电阻之大作用——CAN终端电阻
查看>>
Length of Last Word
查看>>
c#序列化应用
查看>>
centos 打印java 堆栈信息
查看>>
APDU指令返回码及其代表含义
查看>>
Kivy / Buildozer VM Ubuntu不能连接到网络的问题解决
查看>>
PHP之Error与Logging函数讲解
查看>>
Dedecms最新版本存储型XSS
查看>>
idea下http响应乱码
查看>>
mybatis sql模板
查看>>
Thirft框架介绍
查看>>