Excel Sheet Column Title

Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.

For example:

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


Example 1:

Input: columnNumber = 1
Output: "A"

Example 2:

Input: columnNumber = 28
Output: "AB"

Example 3:

Input: columnNumber = 701
Output: "ZY"


Constraints:

  • 1 <= columnNumber <= 231 - 1

My Solution

We can solve this with a StringBuilder to add characters to the column title in place in Java. Every character would be (columnNumber % 26) added to the ASCII value of ‘A’. Then at each iteration we divide columnNumber by 26. One detail also is that the columnNumber is offset by 1, so we need to subtract 1 from columnNumber before passing to the modulo of 26 and we need to subtract 1 from columnNumber before dividing by 26. Finally the column title string will be in reverse order, so we just need to reverse the StringBuilder and call toString() to return the string.

Time complexity would be O(log n), where n is the column number because we divide by 26 at each iteration. Space complexity would also be O(log n) for the column title.

class Solution {
    public String convertToTitle(int columnNumber) {
        StringBuilder sb = new StringBuilder();

        while (columnNumber > 0) {
            sb.append((char)('A' + ((columnNumber-1) % 26)));
            columnNumber = (columnNumber-1) / 26;
        }

        return sb.reverse().toString();
    }
}
Previous
Previous

Majority Element

Next
Next

Intersection of Two Linked Lists