1010 Radix (25分) (C/C++)

考点:进制转换、整型溢出、二分

#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>

typedef long long LL;
using namespace std;

//将base进制转换为10进制
LL get_value(string s, int base){
    LL sum = 0;
    int digit;
    LL exp = 1;
    for(int i = s.size() - 1; i >= 0; i--){
        if(isdigit(s[i])) digit = s[i] - '0';
        else digit = s[i] - 'a' + 10;
        sum += digit * exp;
        exp *= base;
        }
    return sum;
}

int main(void){
    string s1, s2;
    int tag, radix, ans;
    cin >> s1 >> s2 >> tag >> radix;
    if(tag == 2) swap(s1, s2);
    LL target = get_value(s1, radix);
    LL l = 2;    //s2至少需要的进制
    for(int i = 0; i < s2.size(); i++){
        if(isdigit(s2[i])) l = max(l, (LL)s2[i] - '0' + 1);
        else l = max(l, (LL)s2[i] - 'a' + 10 + 1);
        }
    LL r = max(target, l);	//确定二分下界
    bool check = false;
    while(l <= r){
        LL mid = (l + r) >> 1;
        LL tmp = get_value(s2, mid);
        if(tmp == target){
            check = true;
            ans = mid;
            break;
            }
        //tmp < 0表示运算溢出
        else if(tmp < 0 || tmp > target) r = mid - 1;
        else l = mid + 1;
        }
    if(check) printf("%d\n", ans);
    else puts("Impossible");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值