Column Name of a given column number

Problem Statement – Given a positive integer, return its corresponding column title as appear in an Excel sheet. Excel columns has a pattern like A, B, C, … ,Z, AA, AB, AC,…. ,AZ, BA, BB, … ZZ, AAA, AAB ….. etc.

In other words, column 1 is named as “A”, column 2 as “B”, column 27 as “AA” and so on.

Example

Given Input: N = 28

Expected Output: AB Explanation: 1 to 26 are A to Z. Then, 27 is AA and 28 = AB.

Logic

1] Initialize variables op as an output string and alpha to store all the letters of the alphabet.

2] Fill the alphabet array

See also  Roman Number to Integer

3] Loop as long as n is greater than 0

4] Calculate the reminder, to determine the character for the current position in the excel column name

5] Append the corresponding character from the alpha array to the result output

6] Now update the value of n for the next iteration

7] Return the result

import  java.util.*;
public class Main {
    public static void main(String[] args) {
        long s=28;
        System.out.println(colName(s));
    }
    static String  colName (long n)
    {
        String op = "";
        char alpha[] = new char[26];
        alpha[0] = 'A';
        for (int i = 1; i < 26; i++)
            alpha[i] = (char) ((int) alpha[i - 1] + 1);

        while (n > 0)
        {
            long rem = (n - 1) % 26;
            op = alpha[(int) rem] + op;
            n = (n - 1) / 26;
        }
        return op;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

WhatsApp Icon Join For Job Alerts