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

前端 未结 28 1326
[愿得一人]
[愿得一人] 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 23:02

    This version is purely functional and permits alternative 'code' sequences, for example if you wanted to only uses the letters 'A' to 'C'. In Scala, with a suggestion from dcsobral.

    def columnNumber(name: String) = {
        val code = 'A' to 'Z'
    
        name.foldLeft(0) { (sum, letter) =>
            (sum * code.length) + (code.indexOf(letter) + 1)
        }
    }
    

提交回复
热议问题