Leetcode 168. Excel Sheet Column Title
Given a positive 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
...
columnNumber
that we need to handle?
columnNumber
will be a positive integer and can be assumed to be within typical integer bounds for coding contests.public class ExcelColumnTitle {
public static String convertToTitle(int columnNumber) {
StringBuilder columnTitle = new StringBuilder();
while (columnNumber > 0) {
columnNumber--; // adjust columnNumber to be zero-indexed
int remainder = columnNumber % 26;
columnTitle.append((char) ('A' + remainder));
columnNumber = columnNumber / 26;
}
return columnTitle.reverse().toString();
}
public static void main(String[] args) {
// Test examples
System.out.println(convertToTitle(1)); // Output: A
System.out.println(convertToTitle(28)); // Output: AB
System.out.println(convertToTitle(701)); // Output: ZY
}
}
columnNumber
by 1. This adjustment helps in handling the 1-based index system used in the problem description.columnNumber
. This will give a number between 0 and 25, which corresponds to characters ‘A’ to ‘Z’.StringBuilder
.columnNumber
by 26 to handle the next ‘digit’ in the sequence.StringBuilder
because the characters were appended in a reverse order.columnNumber
. This is because in each iteration, we divide the number by 26, reducing the problem size logarithmically.The problem is approached in a straightforward and efficient manner, using basic operations and a string builder for constructing the final result. This ensures that the solution is both easy to understand and optimal for the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?