1010 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.
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.

输入格式

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.

输出格式

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.

输入样例1

6 110 1 10

输出样例1

Sample Output 1:
2

输入样例2

1 ab 1 2

输出样例2

Impossible

题目大意

给出两个正数n1、n2,以及其中一个数的进制数radix,求另一个数可能的进制数,使n1 == n2成立。

思路

基本的思想是先把n1(进制数已知)转换为十进制,再通过枚举n2的可能进制数,将n2也转换为十进制。再将两个十进制数比较,相等即返回。
但是,我最初找n2进制数的方法是暴力枚举,因为没有考虑到进制数可以取的非常大(如n1为十进制的10^10,而n2为1),有一个测试点运行超时。
因此,最好的办法是运用二分查找,下界为n2最小位的值+1,上界(不取)为n1的值+1。注意不是查找到一个进制数就结束,而是要与之前的比较,找到最小的符合题意的进制数
这里还会遇到一个严重的问题,即便我已把数据设为long long,由于n2可取的进制数太大,在将n2转化为十进制时仍然有可能溢出。解决办法是,在将其转化为十进制时,不断地判断结果是否小于0,若小于0则直接返回一个-1,表示上溢。在找进制数时,一旦得到n2转换后的值为-1,便可知该进制数取得太大。

AC代码

#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long ll;

//将r进制数转化为十进制 
ll to_10(ll r, string n){
	ll num = 0;
	for(int i = 0; i < n.size(); i++){
		int a;
		if(n[i] >= '0' && n[i] <= '9')
			a = n[i] - '0';
		else a = n[i] - 'a' + 10;
		num += pow(r, n.size() - 1 - i) * a;
		if(num < 0) //数据溢出 
			return -1;
	}
	return num;
}

int main(){
	string n1, n2;
	//n1的进制给出,n2未给出
	ll tag, radix;
	cin>>n1>>n2>>tag>>radix;
	if(tag == 2)
		swap(n1, n2);
	ll t1 = to_10(radix, n1);
	//以下找出n2最小的可能进制数
	ll r_min = 2;
	for(int i = 0; i < n2.size(); i++){
		ll a;
		if(n2[i] >= '0' && n2[i] <= '9')
			a = n2[i] - '0';
		else a = n2[i] - 'a' + 10;
		if(a + 1 > r_min)
			r_min = a + 1;
	} 
	ll r_max = t1 + 1; //最大的可能进制数 
	bool flag = false; //是否存在合适的进制数 
	//以下进行二分查找,找出符合条件的进制数 
	ll mid, ans = r_max;
	while(r_min <= r_max){
		mid = (r_min + r_max) / 2;
		ll t2 = to_10(mid, n2);
		if(t2 == t1){
			flag = true;
			ans = min(ans, mid);
			r_max = mid - 1;
		}
		else if(t2 > t1 || t2 < 0)
			//t2<0同样代表进制数太大 
			r_max = mid - 1;
		else
			r_min = mid + 1;
	}
	if(flag) cout<<ans;
	else cout<<"Impossible";
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值