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

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

    Caveat: both of these versions assume only uppercase letters A to Z. Anything else causes a miscalculation. It wouldn't be hard to add a bit of error checking and/or uppercasing to improve them.

    Scala

    def excel2Number(excel : String) : Int = 
      (0 /: excel) ((accum, ch) => accum * 26 + ch - 'A' + 1)
    

    Haskell

    excel2Number :: String -> Int
    excel2Number = flip foldl 0 $ \accum ch -> accum * 26 + fromEnum ch - fromEnum 'A' + 1
    

提交回复
热议问题