Converts an integer to alphabetical form (base26) - Java java.lang

Java examples for java.lang:char

Description

Converts an integer to alphabetical form (base26)

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        int n = 42;
        System.out.println(integerToLowerCaseAlphabeticalIndex(n));
    }/*from   w w w.  j  a va 2 s .  c  o  m*/

    /**
     * From: http://stackoverflow.com/questions/11969840/how-to-convert-a-base-10-number-to-alphabetic-like-ordered-list-in-html
     * Converts an integer to alphabetical form (base26)
     * 1 - a
     * 2 - b
     * ...
     * 26 - z
     * 27 - aa
     * 28 - ab
     * ...
     * 
     * @param n - number to convert
     */
    public static String integerToLowerCaseAlphabeticalIndex(int n) {
        String result = "";
        while (n > 0) {
            n--; // 1 => a, not 0 => a
            int remainder = n % 26;
            char digit = (char) (remainder + 97);
            result = digit + result;
            n = (n - remainder) / 26;
        }
        return result;
    }
}

Related Tutorials