PAT甲级1010 Radix (25 分)【二分查找+进制转换】

博客围绕进制转换问题展开,给定两个正整数及其中一个数的进制,需找出另一个数的进制使两数相等。单纯模拟有测试点无法通过,解题采用二分查找法,通过比较当前进制与转换数大小调整查找范围,解决了问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

题意:进制转换,给出2个数,后面跟着tag,和radix的值,tag表示第几个数的进制是radix,要找出另外一个数的进制能和这个radix进制的数相等。题目没给出进制的范围,所以需要用到long long类型。

解题思路:这题单纯模拟有4个测试点过不了,所以扣了4分,然后通过看别人博客的解题思路,才知道要用二分法查找,当时没多想就顺序搜索,看了他们的思路,将自己的代码改了一遍。就增加了一个二分查找函数find_radix(string s,int num),将当前的进制和另外一个转换的数比较,如果当前进制比另外一个大,就说明这个进制太大了,但在转换的时候可能会溢出,所以小于0也说明太大了,这时将high=mid-1,如果等于当前的就直接返回这个mid,如果是其他情况,就说明比较小,将low=mid+1,具体见代码

#include<bits/stdc++.h>
using namespace std;
string n1,n2;
long long radix;
long long change(string s,long long r)
{
	int n=s.length(),k=0,sum=0;
	for(int i=n-1;i>=0;i--)
	{ if(isdigit(s[i])) {
		sum+=(s[i]-'0')*pow(r,k);
    }else if(isalpha(s[i]))
		sum+=(s[i]-'W')*pow(r,k);
		k++;
	}
	return sum;
}
long long find_radix(string n,long long num) 
{
	char m=*(max_element(n.begin(),n.end()));
	long long low=(isdigit(m)?m-'0':m-'a'+10)+1;
	long long high=max(low,num);
	while(low<=high)
	{
		long long mid=(high+low)/2;
		long long sum=change(n,mid);
		if(sum<0||sum>num) high=mid-1;
		else if(sum==num) return mid;
		else  low=mid+1;
	}
	return -1;
}
int main(void)
{
	int tag;
	cin>>n1>>n2;
	cin>>tag>>radix;
	string n,an;
	long long ans;
	if(tag==1) n=n1,an=n2;
	else if(tag==2) n=n2,an=n1;
	ans=find_radix(an,change(n,radix));
	if(ans==-1)printf("Impossible");
	else printf("%lld",ans);
	return 0;
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值