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
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