PU Excel Sheet Column Title

Jan 01, 1970

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

Example:

  • 1 -> A
  • 2 -> B
  • 3 -> C
  • ...
  • 26 -> Z
  • 27 -> AA
  • 28 -> AB

C Solution:

char* convertToTitle(int n) {
    char *res = malloc(64), *r = res;
    while (n--) {
        *r++ = n % 26 + 'A';
        n = n / 26;
    }
    *r = 0;
    char *l = res;
    for (r--; l < r; l++, r--) {
        char c = *l;
        *l = *r;
        *r = c;
    }
    return res;
}

Python Solution:

class Solution(object):
    def convertToTitle(self, n):
        """
        :type n: int
        :rtype: str
        """
        res = []
        while n:
            res.append(chr((n - 1) % 26 + ord('A')))
            n = (n - 1) // 26
        return "".join(res[::-1])

Summary:

  1. Be careful about the corner case, 1 -> A, not 0 -> A.
  2. 0ms, 0%

LeetCode: 168. Excel Sheet Column Title