Programming Riddle: How might you translate an Excel column name to a number?

前端 未结 28 1409
[愿得一人]
[愿得一人] 2020-11-29 22:26

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

28条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 22:44

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

提交回复
热议问题