Question

Formatted question description: https://leetcode.ca/all/168.html

 168	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
 ...

 Example 1:

 Input: 1
 Output: "A"

 Example 2:

 Input: 28
 Output: "AB"

 Example 3:

 Input: 701
 Output: "ZY"

Algorithm

For numbers less than 26, then we only need to take the remainder of 26, then subtract 1 and add the character A.

Code

Java

  • 
    public class Excel_Sheet_Column_Title {
    
        class Solution {
            public String convertToTitle(int n) {
    
                if (n <= 0) {
                    return "";
                }
    
                StringBuilder sb = new StringBuilder();
                while (n > 0) {
    
                    // @note: key is, not n, but n-1
                    int remainder = (n - 1) % 26;
                    sb.insert(0, (char)('A' + remainder)); // @note: reverse order
    
                    n = (n - 1) / 26;
                }
    
                return sb.toString();
            }
        }
    }
    
  • Todo
    
  • class Solution(object):
      def convertToTitle(self, n):
        """
        :type n: int
        :rtype: str
        """
        ans = ""
        while n > 0:
          y = n % 26
          if y == 0:
            char = "Z"
            n -= 26
          else:
            char = chr(ord("A") + y - 1)
          ans += char
          n = n / 26
        return ans[::-1]
    
    

All Problems

All Solutions