4

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
}
7
  • 9
    it's just transforming a number from base26 to decimal (or rather binary, but you don't have to bother about internal representation)
    – Javier
    Commented Mar 8, 2013 at 16:06
  • 1
    @Javier: Not quite. There is no "zero" letter, so it would be like 1111 following 999 instead of 1000.
    – Joe Z.
    Commented Mar 8, 2013 at 16:08
  • 2
    Do you want A=1 or A=0? This matters. Commented Mar 8, 2013 at 16:29
  • can you please check the example?? Commented Mar 8, 2013 at 16:30
  • 10
    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
    Commented Mar 8, 2013 at 18:52

1 Answer 1

16

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;
}
3
  • 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
    Commented Mar 8, 2013 at 16:27
  • @dasblinkenlight pls check my algorithm thanks a lot. Commented Mar 8, 2013 at 16:31
  • 2
    @superxman The result calculation should be result = 26*result + letterValue. Here is a link to ideone with a sample implementation in C#. Commented Mar 8, 2013 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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