/**
 * A class that uses recursion to format a number in any base/radix
 * (in the interval [2, 36])
 *
 * @author  Prof. David Bernstein, James Madison Unversity
 * @verions 1.0
 */
public class RadixFormatter
{
    private final int    MAX_BASE    = 36;
    private final char[] DIGIT_TABLE = {'0','1','2','3','4','5','6','7','8',
					'9','A','B','C','D','E','F','G','H',
					'I','J','K','L','M','N','O','P','Q',
					'R','S','T','U','V','W','X','Y','Z'
                                       };



    /**
     * The "exposed" interface.  This function does
     * initialization and error-checking.
     *
     * @param n    The number to print
     * @param base The base to use
     * @return     The formatted String
     */
    public static String formatInBase(int n, int base)
    {
	String         returnString;
	
	returnString = "";
	if ((base <= 1) || (base > MAX_BASE)) 
	{
	    returnString = "Invalid base: "+base;
	} 
	else 
	{
	    if (n < 0) 
	    {
		returnString = "-";
		n = -n;
	    }

	    returnString += formatRecursively(n, base);
	}

	return returnString;
    }




    /**
     * The recursive function
     *
     * @param n    The number to print
     * @param base The base to use
     */
    private static String formatRecursively(int n, int base)
    {
        // Base Case
        if (n < base) return DIGIT_TABLE[n % base];

        // Refinement
        return formatRecursively(n/base, base)  + DIGIT_TABLE[n % base];
    }
    
}
