Problem
Given an integer columnNumber
, return its corresponding column title as it appears in an Excel sheet.
OR
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
|
|
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Similar problem
Notes
This is just like base 26 number conversion.
Think of it like this. How would you convert a number to binary ? Can you apply the same principle here now that the base is different ?
Solution
Method 1 - Using string builder and division by 26
To solve the problem of converting a positive integer to its corresponding Excel column title, we need to understand the mapping from numbers to Excel column titles (‘A’ to ‘Z’, ‘AA’, ‘AB’, …, etc.), which can be thought of as a base-26 number system but starts from 1 instead of 0.
Steps:
- Initialize Result: Use a
StringBuilder
or a string to collect characters in reverse order as we process the number. - Convert Number to Title:
- Repeat while the number is greater than 0:
- Decrement the number by 1 (to handle the 1-based indexing).
- Compute the remainder when dividing by 26 to get the correct character (from ‘A’ to ‘Z’).
- Append the computed character to the result.
- Update the number by integer division with 26.
- Repeat while the number is greater than 0:
- Reverse and Return Result: After building the result in reverse order, reverse the collected characters to get the final column title.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(log_{26}(n))
, wheren
is the integer being converted. This is because we repeatedly divide the number by 26. - 🧺 Space complexity:
O(log_{26}(n))
because we store characters proportional to the number of digits in base-26.