2015年6月7日星期日

[LeetCode] Excel Sheet Column Title

Problem:

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

Java Code:

public class Solution {
    public String convertToTitle(int n) {
        StringBuilder result = new StringBuilder();
        while (n > 0) {
            char a = n % 26 == 0 ? 'Z' : (char)('A' - 1 + n % 26);
            result.insert(0, a);
            n = (n - 1) / 26;
        }
        return new String(result);
    }
}

没有评论:

发表评论