uva 343 What Base Is This?

该博客讲述了在解决UVA 343问题时遇到的挑战,包括进制转换和理解题目的细节。作者指出,两个数字可以转换为2到36之间的任意进制,并寻找它们相等时的进制。错误地理解了'inclusive'导致了初始的错误,同时也提醒读者要特别注意0进制的情况。文章通过分步解释和注释代码来帮助理解解决问题的策略。

题目:给了两个数,分别可以转成2-36的任意进制,输出相等时的进制。如果都不可以,输出都不行

注意:1  刚开始把两个数存到了两个char数组。刚开始我设置两个数组长度都是10。多次RA后才发现一些很长的就读不进去了。这让我想到看很多大佬的代码。把数组长度define成M,来控制,也可能是为了避免这种问题


2. 题干中有一句话很考验英语“ The bases associatedwith X and Y will be between 1 and 36 (inclusive), and as noted above, need not be the same for X andY . In representing these numbers the digits 0 through 9 have their usual decimal interpretations. ”  注意那个inclusive是放在36后面的。不对!根本就没有1进制。唉。智商呀。所以如果输入两个0,应该是 0 (base 2) = 0 (base 2) ,而不是 0 (base 1) = 0 (base 1)



3 写代码时,一步步的进行,用注释符把代码分成不同的模块


#include <cstdio>
#include <string.h>
#include <cstdlib>
#include <cmath>
#include <ctgmath>
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>

using namespace std;

int main()
{
    char m[50],n[50];//定的太小会出错
    while(cin>>m>>n){
        
        //先求出m,n中最大的数字
        int max_m,max_n;
        max_m = max_n = 0;
        int temp = 0;
        for(int i = 0; i < strlen(m); i ++){
            if((m[i] >= '0') && (m[i] <= '9')){
                temp = (int)m[i] - 48;
            }
            else temp = (int)m[i] - 55;
            
            if(temp > max_m) max_m = temp;
        }
        //   cout<<max_m;
        for(int i = 0; i < strlen(n); i ++){
            if((n[i] >= '0') && (n[i] <= '9')){
                temp = (int)n[i] - 48;
            }
            else temp = (int)n[i] - 55;
            
            if(temp > max_n) max_n = temp;
        }
        //  cout<<max_n;
        
        //0 0情况做特殊处理,因为进制是从2到36的不包括1
        if(max_n==0 && max_m==0) cout<<"0 (base 2) = 0 (base 2)"<<endl;
        else{
            //判断
            int flag = 0;
            for(int i = max_m+1;i<=36 && flag == 0;i++){ //跳出双重循环的技巧!在外层循环中加上一个flag!
                for(int j = max_n+1; j<=36; j++){
                    if (strtol(m, NULL, i) == strtol(n, NULL, j)) {
                        printf("%s (base %d) = %s (base %d)\n",m,i,n,j);
                        flag = 1;
                        break;
                        
                    }
                }
                
            }
            
            if (flag == 0) {
                printf("%s is not equal to %s in any base 2..36\n",m,n);
            }
        }
        
        memset(m, 0, sizeof(m));
        memset(n, 0, sizeof(n));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值