Pages

Monday 1 October 2012

UVA - 343 - What Base Is This?

import java.math.BigInteger;
import java.util.Scanner;

public class Main {

    public static void main(String[] args){
        Scanner s=new Scanner(System.in);
        StringBuffer sb = new StringBuffer("");
        while (s.hasNext()) {
            String temp=s.next().trim();
            String temp2=s.next().trim();
            if("0".equals(temp) && "0".equals(temp2)){
                sb.append(0).append(" (base ").append(2).append(") = ")
                        .append(0).append(" (base ").append(2).append(")\n");
                continue;
            }
            if("0".equals(temp) || "0".equals(temp2)){
                sb.append(temp).append(" is not equal to ").append(temp2).append(" in any base 2..36\n");
                continue;
            }
            int minBase1=minBase(temp);
            int minBase2=minBase(temp2);
            Boolean found=false;
            int indI=0,indJ=0;
            for(int i=minBase1;i<37;i++){
                 for(int j=minBase2;j<37;j++){
                     if(new BigInteger(temp, i).compareTo(new BigInteger(temp2, j))==0){
                         found=true;
                         indI=i;
                         indJ=j;
                         break;
                     }
                 }
                 if(found)
                     break;
            }
            if(indI==0 &&indJ==0)
                sb.append(temp).append(" is not equal to ").append(temp2).append(" in any base 2..36\n");
            else
                sb.append(temp).append(" (base ").append(indI).append(") = ")
                        .append(temp2).append(" (base ").append(indJ).append(")\n");
        }
        System.out.print(sb);
    }

    static int minBase(String temp) {
        int max=-1;
        temp=temp.toUpperCase();
            for(int i=0;i<temp.length();i++){
                if(temp.charAt(i)>='A' && temp.charAt(i)<='Z' ){
                    if(max<temp.charAt(i)-'A'+10)
                        max=temp.charAt(i)-'A'+10;
                }
                else if(temp.charAt(i)>='0' && temp.charAt(i)<='9' ){
                    if(max<temp.charAt(i)-'0')
                        max=temp.charAt(i)-'0';
                }
            }
        return max+1;
    }
}

No comments:

Post a Comment