【PAT】【二分】【进制转换】1010 Radix

#include <iostream>
#include <cstdio>
using namespace std;

//这道题不难,但是坑点真的是非常多,花了非常多的时间才把全部测试点过掉
//pat的数据非常的坑,坑点十足,拿分不难,满分很难

//解题思路:
//题意是给定一个数和其进制,找到使另一个数与其相等的进制
//那么将给定的数转化成十进制,再使用二分查找另一个数的进制
//坑点:转换回十进制很容易就会越过数据大小,会有一组非常大的进制数据卡二分法,要输出满足的最小进制
//二分的两个边界的设定,其中low为第二个数的maxdigit + 1,hign为第一个数的大小num + 1;

typedef long long ll;
//找二分下界,即单位最大的数
int find_mx(const string &t)
{
    int mx(0);
    for(int i = 0; i < t.size(); i++)
    {
        if(isdigit(t[i]))
        {
            mx = max(mx,t[i] - '0');
        }
        else if(islower(t[i]))
        {
            mx = max(mx,t[i] - 'a' + 10);
        }
    }
    return mx;
}

//转化成十进制
void convert(const string &t, ll k, ll &res)
{
    res = 0;
    for(int i = 0; i < t.size(); i++)
    {
        if(isdigit(t[i]))
        {
            res = (t[i] - '0') + res * k;
        }
        else if(islower(t[i]))
        {
            res = (t[i] - 'a' + 10) + res * k;
        }
    }
}

ll num(0);
ll hign, low, ans(-1);
void find_rad(const string &t)
{
//    cout << hign << " " << low << endl;
    ll res(0);
    while(low <= hign)
    {
        ll mid = (hign + low) / 2;
        convert(t, mid, res);
//        当res < 0时已经越界,往下查找
        if(res > num || res < 0)
        {
            hign = mid - 1;
        }
//        相等则保存下来然后继续找更小值
        else if(num == res)
        {
            ans = mid;
            hign = mid - 1;
        }
        else
        {
            low = mid + 1;
        }
    }
}
int t;
int main()
{

    string a, b;
    int tag, rad;
    cin >> a >> b >> tag >> rad;

    string t;
    if(tag == 1) t = a;
    else t = b;
//    先转化第一个数
    convert(t, rad, num);

    if(tag == 1) t = b;
    else t = a;
//    设定二分查找的上下界
    low = find_mx(t) + 1;
    hign = num + 1;
//查找第二个数的进制
    find_rad(t);

    if(ans != -1)
    cout << ans << endl;
    else cout << "Impossible" << endl;
    return 0;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值