Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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
}
share|improve this question
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 Mar 8 '13 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. Mar 8 '13 at 16:08
2  
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
7  
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

1 Answer 1

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.... –  MichaelT Mar 8 '13 at 16:27
    
@dasblinkenlight pls check my algorithm thanks a lot. –  Esteban V Mar 8 '13 at 16:31
1  
@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

 
discard

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.