AdSense

Saturday, January 10, 2015

Excel Sheet Column Title / Excel Sheet Column Number

These two problems are just testing you how to convert from base X (in this case, X = 26) to base 10. The first problem requires us to convert from base 10 to base 26 and the second one asks to the reverse.

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 



public String convertToTitle(int n) {
        if (n <= 0)
            return "";
        String rst = "";
        while (n > 0) {
            int tmp = n % 26;
            n = n / 26;
            if (tmp == 0) {
                rst = "Z" + rst;
                n -= 1;
            }
            else {
               char cha = (char)(tmp + 'A' - 1);
               rst = String.valueOf(cha) + rst;
            }
            
        }
        return rst;
    }


Excel Sheet Column Number

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

public int titleToNumber(String s) {
        if (s == null)
            throw new NullPointerException("Null String!");
        if (s.length() == 0)
            return 0;
        int l = s.length();
        int sum = 0;
        for (int i = 0; i < l; i++) {
            sum += Math.pow(26, l - 1 - i) *(s.charAt(i) - 'A' + 1);
        }
        return sum;
    }

No comments:

Post a Comment