Monday, December 22, 2014

Excel Sheet Column Title

Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 

Nothing special, but it's important to know how to play around with character encoding.


public class ExcelTitle {
    public String convertToTitle(int n) {
        
        if (n < 0)
            throw new Error("Not positive integer");
        StringBuilder sb = new StringBuilder();
        while (n > 0)
        {
            int index = n % 26;
            if (index == 0)
            {
                sb.insert(0, 'Z');
                //trim the excessive digit 
                //e.g., n = 26, n % 26 == 0, n / 26 = 1;
                n -= 26;
            }
            else
                sb.insert(0, Character.toChars('A' + index - 1));
            n /= 26;
        }
        return sb.toString();

No comments:

Post a Comment