I was recently asked in a job interview to resolve a programming puzzle that I thought it would be interesting to share. It\'s about translating Excel column letters to actu
You can do this in C like this:
unsigned int coltonum(char * string)
{
unsigned result = 0;
char ch;
while(ch = *string++)
result = result * 26 + ch - 'A' + 1;
return result;
}
No error checking, only works for upper case strings, string must be null terminated.
Here is another version of this code in Python:
keycode=1
for i in range (1,len(word)):
numtest[i]=word[i-1]
keycode = keycode*26*int(wordtest[numtest[i]])
last=word[-1:]
keycode=keycode+int(wordtest[last])
print(keycode)
print(bin(keycode))
#Numtest and wordtest are dictionaries.
I wrote this ages ago for some Python script:
def index_to_int(index):
s = 0
pow = 1
for letter in index[::-1]:
d = int(letter,36) - 9
s += pow * d
pow *= 26
# excel starts column numeration from 1
return s
Read a column name from STDIN and print out its corresponding number:
perl -le '$x = $x * 26 - 64 + ord for <> =~ /./g; print $x'
Caveats: Assumes ASCII.
EDIT: Replaced "
with '
so that your shell won't interpolate $x
in the string.
Another Delphi one:
function ExcelColumnNumberToLetter(col: Integer): string;
begin
if (col <= 26) then begin
Result := Chr(col + 64);
end
else begin
col := col-1;
Result := ExcelColumnNumberToLetter(col div 26) + ExcelColumnNumberToLetter((col mod 26) + 1);
end;
end;
Delphi:
// convert EXcel column name to column number 1..256
// case-sensitive; returns 0 for illegal column name
function cmColmAlfaToNumb( const qSRC : string ) : integer;
var II : integer;
begin
result := 0;
for II := 1 to length(qSRC) do begin
if (qSRC[II]<'A')or(qSRC[II]>'Z') then begin
result := 0;
exit;
end;
result := result*26+ord(qSRC[II])-ord('A')+1;
end;
if result>256 then result := 0;
end;
-Al.