28/180: GeeksForGeeks: Find excel column names from given column number

Navneet Ojha
1 min readApr 21, 2021

You will be provide with a number and you need to find out the column name. For example

Input              Output
26 Z
51 AY
52 AZ
80 CB
676 YZ
702 ZZ
705 AAC

By excel column numbers to name signifies, for 1 — A, 2 — B, 3 — C, 4 — D and so on, for 26— Z for 27 — ZA

For the solution we need to take the remainder with 26. If remainder with 26 is 0 means 26, 52 and so on, then we add Z in the output string and new n becomes (n/26) — 1, because we are considering 26 to be ‘Z’ while in actually it is 25th with respect to A

If remained comes out be non zero like 1, 2 , 3 and so on then we need to insert the character accordingly in the string and do n = n/26. At the last we reverse the string and print.

Example: n = 700.The remained n%60 is 24, so we put X in the output string and n becomes n/26 which is 26. Remainder for 26%26 is 0, so we put (n/26)-1 which is 0.

public class ExcelColumnNames{
private static void main printString(int colNo){
Stringbuilder colName = new Stringbuilder();
while(columnNo > 0){
int rem = colNo % 26;
if(rem == 0){
colName.append('Z');
colNo = (colNo/26) -1;
}else{
colName.append((char)((rem-1)+'A'));
colNo = colNo/26;
}
}
System.out.println(colName.reverse());
}

--

--

Navneet Ojha

I am Indian by birth, Punjabi by destiny. Humanity is my religion. Love to eat, travel, read books and my million dreams keep me alive.