Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

Ordinal number to spreadsheet label

Sharing is caring!

Problem statement
Write a function that takes the ordinal number of a column in a spreadsheet and returns the label of that column.

1 -> A 
2 -> B 
26 -> Z
27 -> AA
...
703 -> AAA
...

Full code

public class Ordinal2SpreadsheetNumber {

    public static String convert(int n) {
        if (n>=1 && n<=26) {
            return ""+(char)(n + 'A' - 1);
        } else {
            return convert(n/26) + (char)(n % 26 + 'A' - 1);
        }
    }

    public static void main(String[] args) {
        System.out.println(convert(1));
        System.out.println(convert(2));
        System.out.println(convert(3));
        System.out.println(convert(26));
        System.out.println(convert(27));
        System.out.println(convert(28));
        System.out.println(convert(703));
    }
}