Translate

Views

Thursday, July 6, 2023

Solution UVA: 343 - What Base Is This?

 

 Problem  VerdictLangTimeBestRankSubmit Time
 | discuss343 - What Base Is This? AcceptedC++110.0800.000155160 secs ago

Suggest:
- Use brute force algorithm (for for)
+ Note base min is 2 (i have been WA when submit)
+ Note use long long (i have been WA when check uDebug)

#include<bits/stdc++.h>
#define int long long
using namespace std;

int max(int a, int b){
    if (a>b) return a;
    return b;
}

int f(char x){
    if ('A' <= x && x <= 'Z')
        return x-'A'+10;
    return x-'0';
}

int min_base(string s){
    int base= 0;
    for(int i=0; s[i]; i++)
        base= max(base, f(s[i]));
    return max(2, base+1);
}

int ff(string s, int base){
    int b= 0, val=0;
    for(int i=s.size()-1; i>=0; i--)
        val += f(s[i])*pow(base, b++);
    return val;
}

bool fff(string s1, string s2){
    for(int i= min_base(s1); i<=36; i++)    
        for(int j= min_base(s2); j<=36; j++)    
            if (ff(s1, i) == ff(s2, j)) {
                cout<<s1<<" (base "<<i<<") = "<<s2<<" (base "<<j<<")\n";
                return true;    
            }
    return false;
}

int32_t main(){
    ios::sync_with_stdio(false); cin.tie(nullptr);

    string s1, s2;
    while(cin >> s1 >> s2){
        if (!fff(s1, s2)) cout<<s1<<" is not equal to "<<s2<<" in any base 2..36\n";
    }
}

No comments: