PAT(甲) 1010 Radix (25)(详解)

1010.Radix (25)

题目描述:

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.


解题方法:
这道题的根本在于找到另一个数是否能有一个进制可以转换为前者。那么自然而然需要用到遍历的方法,一般的方法如果线性搜索必然是会超时的(注意:进制不仅仅只有2、4、8、16),因此可以考虑用二分法进行搜索。


易错点:
1. 二分法搜索下限为该N进制数最大字符所代表的数字+1,否则第一个无法通过
2. 二分法搜索上限为已确定的数的数值
3. 再用pow函数需要注意里面参数类型,不清楚的可以参考我的另一篇博文


程序:

#include <algorithm>
#include <string.h>
#include <cctype>
#include <cmath>
#include <iostream>
using namespace std;

char FindMaxElement(char ch[])
{   /* 寻找字符数组中最大的元素 */
    return *max_element(ch, ch+strlen(ch));
}

int charToint(char c)
{   /* 把字符转为数字 */
    return isdigit(c) ? c - '0' : c - 'a' + 10;
}

long long transfer(char ch[], long long radix)
{   /* 转换成十进制 */
    long long sum = 0;
    for (int i = strlen(ch)-1; i >= 0; i--)
        sum += charToint(ch[i]) * pow(radix, strlen(ch)-1-i);
    return sum;
}

long long check(char ch[], long long num)
{   /* 采用二分法进行寻找 */
    long long low = charToint(FindMaxElement(ch))+1, mid; /* 这里下界是ch中最大的字符数值+1 */
    long long high = num > low ? num : low;
    while (low <= high)
    {
        mid = (low+high) / 2;
        long long aws = transfer(ch, mid);
        if (aws < 0 || aws > num)
            high = mid - 1;
        else if (aws == num)
            return mid;
        else
            low = mid + 1;
    }
    return -1;
}

int main(int argc, char const *argv[])
{
    char N1[11], N2[11];
    int tag;
    long long r, radix;
    cin >> N1 >> N2 >> tag >> radix;
    r = tag == 1 ? check(N2, transfer(N1, radix)) : check(N1, transfer(N2, radix));
    if (r == -1)
        cout << "Impossible";
    else
        cout << r;
    return 0;
}

如果对您有帮助,帮忙点个小拇指呗~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值