Competitive/Collaborative Programming Class

ICPC Computer Programming Contest Prep

Problem Solving in Computer Science

Fall 2014 -- CSC 2700 Section 01

[Isaac's Home Page ]  [Mailing List ]  [Class Page ]  [Normal ]  

week02/b/Main.java

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

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author ared38
 */
public class Main {
    
    BigInteger base=new BigInteger("26");
    Scanner cin=new Scanner(System.in);

    /**
     * @param args the command line arguments
     */
    void doIt(){
        //String s=cin.next();
        //BigInteger enc=encode(s);
        //System.out.println(formatEncoding(enc));
        //System.out.println(decode(enc));
        
        while(true){
            String word;
            String number;
            String input=cin.next();
            if(input.charAt(0)=='*'){
                break;
            }
            else if(Character.isDigit(input.charAt(0))){
                word=decode(new BigInteger(input));
                number=formatEncoding(new BigInteger(input));
            }
            else{
                word=input;
                number=formatEncoding(encode(input));
            }
            System.out.printf("%-22s%s\n",word,number);
        }
        
    }
    
    BigInteger encode(String word){
        BigInteger result=new BigInteger("0");
        for(char c:word.toCharArray()){
            result=result.multiply(base); //shift
            BigInteger charVal=new BigInteger(((Integer)(c-'a'+1)).toString());
            //System.out.println(c+"->"+charVal);
            result=result.add(charVal);
        }
        return result;
    }
    
    String decode(BigInteger coding){
        String result="";
        while(coding.compareTo(new BigInteger("0"))>0){
            int digit=coding.mod(base).intValue();
            coding=coding.divide(base);
            char cdigit=(char)('a'+digit-1);
            result=cdigit+result;
        }
        return result;
    }
    
    String formatEncoding(BigInteger coding){
        StringBuffer sb=new StringBuffer(coding.toString());
        for(int i=sb.length()-3;i>0;i-=3){
            sb.insert(i, ',');
        }
        return sb.toString();
    }
    
    public static void main(String[] args) {
        (new Main()).doIt();
    }
}

The statements and opinions included in these pages are those of only. Any statements and opinions included in these pages are not those of Louisiana State University or the LSU Board of Supervisors.
© 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014