LeetCode #168 Excel Sheet Column Title Solution & Explanation

LeetCode Problem

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

Solution

In my initial attempt, I utilized a dictionary along with a while loop to extract each letter.

C# Solution

Solution1 – Dictionary

public class Solution {
    
    public string ConvertToTitle(int columnNumber) {
        
        Dictionary<int, string> dict = new Dictionary<int, string>()
        {{0,"Z"},
             {1, "A"},{2,"B"},{3,"C"},{4,"D"},{5,"E"},{6,"F"},{7,"G"},{8,"H"},{9,"I"},{10,"J"},{11,"K"},{12,"L"},{13,"M"},{14,"N"},{15,"O"},{16,"P"},{17,"Q"},{18,"R"},{19,"S"},{20,"T"},{21,"U"},{22,"V"},{23,"W"},{24,"X"},{25,"Y"},{26,"Z"} 
            
        };
        int now = columnNumber;
        string tmp = "";

        while(now>0)
        {
            int m = now%26;
            if(m == 0) { m =26; }
            tmp = dict[m]+tmp;
            now = (now-m)/26;
        }
        
 
        
        return tmp;
    }
}

Time Complexity: O(n)

Solution2 – ASCII code

public class Solution {
    public string ConvertToTitle(int columnNumber) {
        StringBuilder res = new StringBuilder();

        while(columnNumber>0){
            columnNumber-=1;
            var c = (char)('A'+(columnNumber)%26);
            res.Insert(0, c);

            columnNumber/=26;
        }
        return res.ToString();
    }
}

Time Complexity: O(n)

In Excel, columns are numbered starting from 1, where ‘A’ represents the first column. To convert an integer columnNumber to its corresponding column title, we adjust columnNumber by subtracting 1 (columnNumber-=1).

This conversion ensures that we use a zero-based index, allowing us to map the index directly to ASCII characters for generating column titles accurately in Excel.

Klook.com

Conclusion

🧡If my solution helps, that is my honor!

🧡You can support me by sharing my posts, thanks a lot

If you got any problem about the explanation, please feel free to let me know

The problem link : Excel Sheet Column Title – LeetCode

Further reading – Post Related to ASCII code :

Some Random LeetCode posts

Leave a Reply

Your email address will not be published. Required fields are marked *