168. Excel Sheet Column Title
Explanation:
To convert a column number to an Excel column title, we can use a simple algorithm by repeatedly dividing the column number by 26 (the number of letters in the English alphabet) and converting the remainders to corresponding characters.
- Initialize an empty string to store the result.
- While the column number is greater than 0:
- Calculate the remainder of the column number divided by 26.
- Adjust the remainder to be in the range of 1 to 26.
- Convert the remainder to the corresponding character ('A' to 'Z') and append it to the result string.
- Update the column number by subtracting the remainder and dividing by 26.
- Reverse the result string to get the correct order of characters.
- Return the result string as the Excel column title.
Time Complexity: O(log n) where n is the column number, as we are dividing the number by 26 in each iteration.
Space Complexity: O(log n) for storing the result string.
:
class Solution {
public String convertToTitle(int columnNumber) {
StringBuilder result = new StringBuilder();
while (columnNumber > 0) {
columnNumber--;
result.insert(0, (char)('A' + columnNumber % 26));
columnNumber /= 26;
}
return result.toString();
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.