Competitive/Collaborative Programming Class

ICPC Computer Programming Contest Prep

Problem Solving in Computer Science

Spring 2015 -- CSC 2700 Section 01

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

week02/i/NumericallySpeaking.java

/*
 *  Author: Son Pham
 *    Date: January 23, 2013
 * Purpose: Solves this problem using the simplest approach.
 * Problem: 619 - Numerically Speaking
 */

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

public class NumericallySpeaking {

    static String word, number, read;
    static BigInteger[] base = new BigInteger[20];
    
    public static void main(String[] args) {
        
        char type;
        
        for(int i = 0; i < 20; i++){
            base[i] = new BigInteger("26").pow(i);
        }
        
        Scanner reader = new Scanner(System.in);
        read = reader.next();
        while(!(read.equals("*"))){
            if(Character.isDigit(read.charAt(0))){
                type = 'n';
                number = read;
                word = numToWord(number);
            }
            else{
                type = 'w';
                word = read;
                number = wordToNum(word);
            }
            number = insCommas(number);
            word = String.format("%-22s", word);
            System.out.println(word+number);
            read = reader.next();
        }
    }
    
    public static String wordToNum(String s){
        BigInteger calc = new BigInteger("0");
        int length = s.length();
        for (int i = 0, j = length - 1; i < length; ++i, --j){
            int chVal = (int)s.charAt(i) - 96;        
            BigInteger multiple = new BigInteger((""+chVal));
            BigInteger temp = base[j].multiply(multiple);
            calc = calc.add(temp);
        }
        return calc.toString();
    }
    
    public static String numToWord(String s){
        BigInteger value = new BigInteger(s);
        String unmapped = "";
        for(int i = 19; i >= 0; --i){
            if(value.compareTo(base[i]) >= 0){
                BigInteger temp = value.divide(base[i]);
                int chVal = Integer.parseInt(temp.toString());
                char ch = (char)(chVal+96);
                unmapped += ch;
                temp = base[i].multiply(temp);
                value = value.subtract(temp);
            }
        }            
        return unmapped;
    }
    
    public static String insCommas(String s){
        int length = s.length();
        if(length < 4){
            return s;
        }
        else{
            return insCommas(s.substring(0,length-3))+","+s.substring(length-3);
        }
    }
}

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, 2015