Excel column letters to actual numbers, if you recall, Excel names its columns with letters from A to Z, and then the sequence goes AA, AB, AC... AZ, BA, BB, etc. You have to write a function that accepts a string as a parameter (like "AABCCE") and returns the actual column number. And then do the exact reverse, given column number return the column name.
Also verify complexity: \$O(\log n)\$, where \$n\$ is the input number while \$\log\$ is to base the base being considered (hexa, decimal or binary etc.).
public final class Excel {
private Excel() {}
public static int getExcelColumnNumber(String column) {
int result = 0;
for (int i = 0; i < column.length(); i++) {
result *= 26;
result += column.charAt(i) - 'A' + 1;
}
return result;
}
public static String getExcelColumnName(int number) {
final StringBuilder sb = new StringBuilder();
int num = number - 1;
while (num >= 0) {
int numChar = (num % 26) + 65;
sb.append((char)numChar);
num = (num / 26) - 1;
}
return sb.reverse().toString();
}
public static void main(String[] args) {
Assert.assertEquals(53, getExcelColumnNumber("BA"));
Assert.assertEquals("BA", getExcelColumnName(53));
Assert.assertEquals(703, getExcelColumnNumber("AAA"));
Assert.assertEquals("AAA", getExcelColumnName(703));
Assert.assertEquals(26, getExcelColumnNumber("Z"));
Assert.assertEquals("Z", getExcelColumnName(26));
Assert.assertEquals(702, getExcelColumnNumber("ZZ"));
Assert.assertEquals("ZZ", getExcelColumnName(702));
}
}