Integer to Letter Mapping
If you need to map an integer value to a letter value, for example: 0 = A, 1 = B, 2 = C, etc., you can follow this advice:
public static String getCharForNumber(int i){
// return null for bad input
if(i < 0){
return null;
}
// convert to base 26
String s = Integer.toString(i, 26);
char[] characters = s.toCharArray();
String result = "";
for(char c : characters){
// convert the base 26 character back to a base 10 integer
int x = Integer.parseInt(Character.valueOf(c).toString(), 26);
// append the ASCII value to the result
result += String.valueOf((char)(x + 'A'));
}
return result;
}
I generalized the algorithm to make use of base 26 conversion in order to deal with a list size greater than 26. It is worthwhile to note that the value BA, and not AA as some may expect, follows Z.
Written by Kyle Binns
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Java
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#