题目来源:PTA(甲级)1010 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
题目大意:
输入两个数可能包含小写字母,1或者2,进制大小。第三个数为代表第一个数是第四个数进制的,求第二个数等于第一个数时进制的大小,不可能则输出Impossible,第三个数为2代表第二个数是第四个数进制的,求第一个数等于第二个数时进制的大小,不可能则输出Impossible。数字的位数最多是十位。
- 求出已给基数的数字的大小,利用二分查找另一个数字的基数
注意事项:
- 虽然定义为long long仍然会出现溢出的现象,不妨直接按照 <0 进行计算
//二分查找
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
string s1, s2;
int tag, radix;
cin >> s1 >> s2 >> tag >> radix;
if (tag == 2)
swap(s1, s2);//如果给是第二个数的基数,则把两个数进行交换位置
int len1 = s1.length(), len2 = s2.length();
long long num1 = 0;
for (int i = 0;i < len1;i++)
{ //计算第一个数的大小
num1 *= radix;
if (s1[i] >= '0'&&s1[i] <= '9')
num1 += s1[i] - '0';
else
num1 += s1[i] - 'a' + 10;
}
long long left, right, mid = 0;
int rax = 0;
for (int i = 0;i < len2;i++)
{ //计算第二个数有可能会出现的最小基数
if (s2[i] >= '0'&&s2[i] <= '9')
rax = max(rax, s2[i] - '0');
else
rax = max(rax, s2[i] - 'a' + 10);
}
left = rax + 1;
right = max(left, num1);
while (left <= right)
{ //利用二分查找第二数合适的基数大小
long long num2=0;
mid = left + (right - left) / 2; //防止溢出,其实longlong不会
for (int i = 0;i < len2;i++)
{ //计算当前基数的情况下,第二个数的大小
num2 *= mid;
if (s2[i] >= '0'&&s2[i] <= '9')
num2 += s2[i] - '0';
else
num2 += s2[i] - 'a' + 10;
}
if (num2 > num1 || num2 < 0) //num2<0就是考虑longlong溢出
right = mid - 1;
else if (num2 < num1)//溢出num2<0,必然num2<num1
left = mid + 1;
else
{
cout << mid << endl;
return 0;
}
}
cout << "Impossible" << endl;
return 0;
}
Tip:
求二分中间值用 mid = left + (right - left) / 2
而不用 mid = (right + left) / 2
防止溢出,具体解释:https://blog.csdn.net/luzhensmart/article/details/101039406