Feb 02

There are a couple of ways to approach the problem of converting a spreadsheet column number to a spreadsheet style label. The following shows how our column numbers need to be mapped:

0 -> A
1 -> B
2 -> C

25 -> Z
26 -> AA
27 -> AB

Firstly using recursion:

    public static String getColumnLabel(int columnNumber) {
    	char c = (char) ('A' + (columnNumber % 26));
        if (columnNumber<26) {
         return Character.toString(c);
       } else {
         return getColumnLabel(columnNumber/ 26 - 1)+c;
       }
    }

And secondly using a loop instead of recursion:

    public static String getColumnLabel(int columnNumber) {
        StringBuilder result = new StringBuilder();
        for (; columnNumber >= 0; columnNumber = columnNumber / 26 - 1) {
            result.insert(0, (char)(columnNumber % 26 +'A'));
        }
        return result.toString();
    }

written by objects \\ tags: ,

Jan 31

The following example shows how recusion can be used to convert any number from 0 to 99 into words. eg. NumberToWords.numberToWords(34) returns “Thirty Four”.


public class NumberToWords {
	
	private static final String[] ONES = { 
		"Zero", "One", "Two", "Three", "Four", "Five",
		"Six", "Seven", "Eight", "Nine" };
	private static final String[] TEENS = { 
		"Ten", "Eleven", "Twelve", "Thirteen", null, "Fifteen",
		null, null, "Eighteen", null };
	private static final String[] TENS = {
		null, null, "Twenty", "Thirty", "Forty", "Fifty",
		"Sixty", "Seventy", "Eighty", "Ninety" };

	public static String numberToWords(int number) {
		if (number<10) {
			return ONES[number];
		} else if (number<20) {
			int n = number - 10;
			String words = TEENS[n];
			return words==null ? ONES[n]+"teen" : TEENS[n]; 
		} else {
			int n = number % 10;
			return TENS[number/10] + 
				(n==0 ? "" : (" " + numberToWords(n)));
		}
	}

	public static void main(String[] args) {
		for (int i=0; i<100; i++) {
			System.out.println(i+" "+numberToWords(i));
		}
	}
}

written by objects \\ tags: , ,