Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


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++)
    Case A:
     result=+ result+26*(LetterValue)^i
share|improve this question
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?? – Esteban V 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
up vote 14 down vote accepted

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;
share|improve this answer
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. – Esteban V 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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.