PAT甲级1010(进制)

1010 Radix (25 point(s))

  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 N​1 and N​2, 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

题目大意

  给定一个数字N1及其进制,问给定的另一个数字N2在什么 进制下等N1

解题思路

  首先把N1转化为10进制,再用二分法求N2与N1相等的进制,上界是N1的十进制数,下界是N2中最大数字+1,详见代码

代码

#include 
#include 
#include 
using namespace std;

long long toNum(char c)
{
	int num;
	if (c >= '0' && c <= '9')
		num = c - '0';
	else num = c - 'a' + 10;
	return num;
}
long long trans(string n_str, long long radix)//将radix进制数转化为十进制数
{
	long long tmp = 1, sum = 0;
	for (int i = n_str.size() - 1; i >= 0; --i)
	{
		sum += tmp * toNum(n_str[i]);
		tmp *= radix;
		if (sum < 0 || tmp < 0)//如果溢出,返回-1
			return -1;
	}
	return sum;
}

int main()
{
	string N1, N2;
	int tag, radix;
	cin >> N1 >> N2 >> tag >> radix;
	long long l, r, mid, base;
	if (tag == 2)
		swap(N1, N2);
	l = 2;
	base = r = trans(N1, radix);//右边界为基准数
	for (auto& item : N2)
	{
		l = max(l, toNum(item) + 1);//左边界为最低进制数
	}
	while (r >= l)//采用二分法,否则超时
	{
		mid = (l + r) >> 1;
		long long t = trans(N2, mid);
		if (t >= base || t < 0)//此处有=的原因是题目要求输出最小进制
			r = mid - 1;
		else l = mid + 1;

	}
	if (trans(N2, l) == base)//l保证符合要求的结果最小
		cout << l;
	else
		printf("Impossible");
	return 0;
}

你可能感兴趣的:(PAT甲级)