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
Coincidentally I've solved the same problem using javascript
$(function() { //shorthand document.ready function
var getNumber = function(x) {
var result = 0;
var multiplier = 1;
for ( var i = x.length-1; i >= 0; i--)
{
var value = ((x[i].charCodeAt(0) - "A".charCodeAt(0)) + 1);
result = result + value * multiplier;
multiplier = multiplier * 26;
}
return result;
};
$('#form').on('submit', function(e) { //use on if jQuery 1.7+
e.preventDefault(); //prevent form from submitting
var data = $("#number").val();
$('#answer').text(getNumber(data));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="form">
<input type="text" id="number"></input>
<button>submit</button>
</form>
<p id="answer"></p>
var getNumber = function(x) {
var result = 0;
var multiplier = 1;
for ( var i = x.length-1; i >= 0; i--)
{
var value = ((x[i].charCodeAt(0) - "A".charCodeAt(0)) + 1);
result = result + value * multiplier;
multiplier = multiplier * 26;
}
return result;
};
http://jsfiddle.net/M7Xty/1/
def ExcelColumnToNumber(ColumnName):
ColNum = 0
for i in range(0, len(ColumnName)):
# Easier once formula determined: 'PositionValue * Base^Position'
# i.e. AA=(1*26^1)+(1*26^0) or 792=(7*10^2)+(9*10^1)+(2*10^0)
ColNum += (int(ColumnName[i],36) -9) * (pow(26, len(ColumnName)-i-1))
return ColNum
p.s. My first Python script!
Common Lisp:
(defun excel->number (string)
"Converts an Excel column name to a column number."
(reduce (lambda (a b) (+ (* a 26) b))
string
:key (lambda (x) (- (char-int x) 64))))
edit: the inverse operation:
(defun number->excel (number &optional acc)
"Converts a column number to Excel column name."
(if (zerop number)
(concatenate 'string acc)
(multiple-value-bind (rest current) (floor number 26)
(if (zerop current)
(number->excel (- rest 1) (cons #\Z acc))
(number->excel rest (cons (code-char (+ current 64)) acc))))))
In Python, without reduce:
def transform(column_string):
return sum((ascii_uppercase.index(letter)+1) * 26**position for position, letter in enumerate(column_string[::-1]))
In Mathematica:
FromDigits[ToCharacterCode@# - 64, 26] &
Assuming column A = 1
int GetColumnNumber(string columnName)
{
int sum = 0;
int exponent = 0;
for(int i = columnName.Length - 1; i>=0; i--)
{
sum += (columnName[i] - 'A' + 1) * (GetPower(26, exponent));
exponent++;
}
return sum;
}
int GetPower(int number, int exponent)
{
int power = 1;
for(int i=0; i<exponent; i++)
power *= number;
return power;
}