Monday, April 20, 2015

[LeetCode] Excel Sheet Column Number and Title Conversion

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 
Solution: The base is 26, and the tricky part is minus 1 first before the conversion.
public class Solution {
    public String convertToTitle(int n) {
        String s = "";
        while (n > 0) {
            n--;
            char ch = (char)('A' + n % 26);
            s = ch + s;
            n /= 26;
        }
        return s;
    }
}


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 

Solution: The base is 26, and the tricky part is plus 1 first before the conversion.
public class Solution {
    public int titleToNumber(String s) {
        if (s.isEmpty()) return 0;
        int mul = 1;
        int num = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            num += (s.charAt(i) - 'A' + 1) * mul;
            mul *= 26;
        }
        return num;
    }
}

No comments:

Post a Comment