Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert letter to digits

Tags:

java

I want to change the letters A to point 1 and so the letter Z to be number 26, then changed again to number 27 letters AA, AB to 28. How do I? Do I have to use the "switch"? I use java program.

like image 452
Leostrada Avatar asked Feb 04 '23 00:02

Leostrada


1 Answers

Did not test this, but something along these lines should work:

public String numberToCharacterRepresentation(int number) {
  char[] ls = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
  String r = "";
  while(true) {
    r = ls[number % 26] + r;
    if(number < 26) {
      break;
    }
    number /= 26;
  }
  return r;
}

The reverse:

public int stringToNumber(String str) {
  char[] ls = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
  Map<Character, Integer> m = new HashMap<Character, Integer>();
  int j = 0;
  for(char c: ls) {
    m.put(c, j++);
  }
  int i = 0;
  int mul = 1;
  for(char c: new StringBuffer(str).reverse().toString().toCharArray()) {
    i += m.get(c) * mul;
    mul *= ls.length;
  }
  return i;
}
like image 180
icyrock.com Avatar answered Feb 05 '23 16:02

icyrock.com