UVALive 4660 A+B【进制】

Given two integers A and B that are not necessarily in base-10, find the smallest possible A + B inbase-10.

  For example,

    A = 213 possibly base-4 (39 in base-10)

    B = 4721 possibly base-8 (2513 in base-10)

    A + B = 39 + 2513 = 2552

Input

First line of the input contains a positive integer T (1 ≤ T ≤ 100), the number of cases. Each casecontains two positive integers A and B. A and B will contain at most 5 digits, each digit will bebetween 0 and 9, inclusive, and no leading zeroes.

Output

For each case, output an integer in base-10 denoting the smallest possible A + B.

Sample Input

3

213 4721

1001 90

638 241

Sample Output

2552

99

592


Regionals 2009 >> Asia - Jakarta


问题链接UVALive 4660 A+B

问题分析

  这是一个进制问题,输入的两个数不知道是几进制,也就是几进制都可以,求的是两个数最小的和,结果以10进制输出。

  对于输入的两个数来说,进制越小值越小,所以尽可能选进制小的。最小的可能的进制就是一串数字中最大的数字加上1。只要两个数的进制知道了,事情就好办了。

  另外,需要详细知道函数atoi()的原理,才能够随心所欲地解决进制有关的问题。

程序说明

  程序中,使用字符流读方式,使用函数getchar()读入数据,同时求得数的最小进制。

  封装了一个函数atoi()来实现字符串转整数。


AC的C语言程序如下:

/* UVALive4660 A+B */

#include <stdio.h>

typedef unsigned long long ULL;

#define MAXN 100

ULL atoi(char *p, int base)
{
    ULL result = 0;

    while(*p) {
        result *= base;
        result += *p - '0';
        p++;
    }

    return result;
}

int main(void)
{
    int n, sbase, tbase, i;
    char c, s[MAXN], t[MAXN];
    ULL val1, val2;

    scanf("%d", &n);
    getchar();
    while(n--) {
        sbase = 0;
        i = 0;
        while((c = getchar()) != ' ') {
            if(c > sbase)
                sbase = c;
            s[i++] = c;
        }
        s[i] = '\0';
        sbase = sbase - '0' + 1;

        tbase = 0;
        i = 0;
        while((c = getchar()) != '\n' && c != EOF) {
            if(c > tbase)
                tbase = c;
            t[i++] = c;
        }
        t[i] = '\0';
        tbase = tbase - '0' + 1;

        val1 = atoi(s, sbase);
        val2 = atoi(t, tbase);

        printf("%lld\n", val1 + val2);
    }

    return 0;
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值