[LeetCode] #168 Excel Sheet Column Title

#168 Excel Sheet Column Title

Question

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 

Thinking

此題的重點是要利用ASCII去換算對應的字元,而我們可能不知道首字母A的ASCII,因此以字元'A'來運算是較佳的選擇

My C# Solution

public class Solution {
    public string ConvertToTitle(int n) {
        var result = string.Empty;
        while(n > 0)
        {
            n--;
            result = Convert.ToChar((n % 26) + 'A') + result;
            n /= 26;
        }
        return result;
    }
}