0

I am looking for easy way of converting letter to number. In result I need to get.

A - 1, B - 2, C -3 ... Z-26, AA - 27, AB -28

and so on.

For now, I just created code for converting all letters from [A - Z]

public static int getNumber(String str) {
    char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    Map<Character, Integer> letterWithNumbers = new HashMap<>();
    int counter = 1;
    for(char c: alphabet) {
        letterWithNumbers.put(c, counter ++);
    }
    return letterWithNumbers.get(str.charAt(0));
}

How can we convert the next values?

Edit: Thanks to Zeb in comments the answer is:

public static int getNumber2(String str) {
    int result = 0;
    char[] alph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    Map<Character, Integer> vals = new HashMap<>();
    int i = 1;
    for(char c: alph){
        vals.put(c, i++);
    }
    char[] strChar = new StringBuilder(str).reverse().toString().toCharArray();
    int base = alph.length;
    int pow = 0;
    for(char c: strChar){
        result+=vals.get(c) * Math.pow(base, pow++);
    }
    return result;
}
slisnychyi
  • 1,832
  • 3
  • 25
  • 32
  • Its just summing up each letter, so do a look foe each letter in the string using substring then keep track by having a sum+=getNumber(currLetter) – Zac May 21 '14 at 17:42
  • It's not a duplicate becouse we need to get number by string. Not string by number as in question. And also it's java not excel – slisnychyi May 21 '14 at 17:45
  • @Zeb, thanks for answer. But for example we have string = AA. in your case it would be 2, but we need 27 – slisnychyi May 21 '14 at 17:47
  • 2
    so its, base 26 so if is AA then you have the digits 1 and 1, but rather then 1 + 1 its really (1 * 26^1) + (1 * 26^0). So start at the end of the string and work to the front and (assuming i is your loop var) do: ` sum += getNumber(currLetter)*Math.pow(26, i)` – Zac May 21 '14 at 17:50

0 Answers0