Convert letters to numbers

I have the following problem.

Given A=1, B=2 , ... , Z =26

I need an algorithm that given a letter combination, like the column order in excel, returns me the number/

AA=27 AB=28

ABC?

Thanks a lot

This is my algorithm so far, I dont like the switch inside the for. Any help is appreciate it, I will write it later in c#

Given A=1, B=2, Z=26. AB=27, ABC?
Variable = ABC
Positions =  Variable.Length -1
Int  result= 0
FOR (i=0; i<= Positions; i++)
{
Letter=Variable[i];
Switch(Letter)
Case A:
LetterValue=1
result=+ result+26*(LetterValue)^i
}
• it's just transforming a number from base26 to decimal (or rather binary, but you don't have to bother about internal representation) – Javier Mar 8 '13 at 16:06
• @Javier: Not quite. There is no "zero" letter, so it would be like 1111 following 999 instead of 1000. – Joe Z. Mar 8 '13 at 16:08
• Do you want A=1 or A=0? This matters. – Jimmy Hoffa Mar 8 '13 at 16:29
• can you please check the example?? – Luis Valencia Mar 8 '13 at 16:30
• For the people who voted to migrate this to Stack Overflow, our FAQ defines "algorithm and data structure concepts" belong here. This question is not about an implementation in a particular language, so it does indeed belong here. – Thomas Owens Mar 8 '13 at 18:52

Think of a sequence of letters as a base-26 number: each letter represents a digit; each position N's value is 26^N (N is zero-based). This is similar to converting decimal numbers to integer values, except you have letters as your digits, and 26 instead of ten as your base.

Now the algorithm is clear: start from the left, and convert letters to numbers. If you see more digits to the right, multiply the result you've got so far by 26, and use that as your initial number for your next iteration. Here is a simple implementation in C#:

private static int FromBase26(string s) {
int res = 0;
foreach (var c in s) {
int d = c - 'A' + 1;
res = 26 * res + d;
}
return res;
}
• The first chardigit is a 1-26 range, everything after that is a 0-25 range. Wait, that isn't exactly right... because then Z and AA would be equivalent.... – user40980 Mar 8 '13 at 16:27
• @dasblinkenlight pls check my algorithm thanks a lot. – Luis Valencia Mar 8 '13 at 16:31
• @superxman The result calculation should be result = 26*result + letterValue. Here is a link to ideone with a sample implementation in C#. – dasblinkenlight Mar 8 '13 at 17:34