PAT1010 Radix

PAT1010 Radix

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.

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: N 1 N1 N1 N 2 N2 N2 t a g tag tag r a d i x radix 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

解题思路:
二分+防止溢出(数据范围超出 l o n g long long l o n g long long

#include<iostream>
#include<cstdio> 
#include<string>
#define ll long long 
using namespace std;
int number(char t){
	if(t>='0'&&t<='9') return t-'0';
	else if(t>='a'&&t<='z') return t-'a'+10;
	return -1;
}
ll trans(string s,ll radix){
	ll ans=0,temp=1;
	for(int i=s.size()-1;i>=0;i--){
		ans+=number(s[i])*temp;
		temp*=radix;
	}
	if(ans<0)  return -1;//溢出 
	return ans;
}
int main(int argc, char** argv) {
	string s[2];
	cin>>s[0]>>s[1];
	int tag,radix;
	scanf("%d%d",&tag,&radix);
	int minv=-1; 
	int ind=tag-1;//0,1
	int ind2=1-ind;
	string n1=s[ind],n2=s[ind2];
	for(int i=0;i<n2.size();i++){
		if(number(n2[i])>minv) minv=number(n2[i]);//rad>=minv+1 
	}
	
	ll num1=trans(n1,radix);
	int flag=0;
	ll l=minv+1,r=num1>l?num1:l,mid=-1;//num1溢出时可能为-1
	while(l<=r){
		mid=(l+r)>>1;
		if(trans(n2,mid)>num1||trans(n2,mid)==-1) r=mid-1;//trans(n2,mid)可能溢出
		else if(trans(n2,mid)<num1) l=mid+1;
		else {
			flag=1;break;
		}
	}
	if(!flag) printf("Impossible");
	else printf("%lld",mid);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值