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

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

    …just needed a solution for PHP. This is what I came up with:

    /**
     * Calculates the column number for a given column name.
     *
     * @param string $columnName the column name: "A", "B", …, "Y", "Z", "AA", "AB" … "AZ", "BA", … "ZZ", "AAA", …
     *
     * @return int the column number for the given column name: 1 for "A", 2 for "B", …, 25 for "Y", 26 for "Z", 27 for "AA", … 52 for "AZ", 53 for "BA", … 703 for "AAA", …
     */
    function getColumnNumber($columnName){
        //  the function's result
        $columnNumber = 0;
    
        //  at first we need to lower-case the string because we calculate with the ASCII value of (lower-case) "a"
        $columnName = strtolower($columnName);
        //  ASCII value of letter "a"
        $aAsciiValue = ord('a') - 1;
    
        //  iterate all characters by splitting the column name
        foreach (str_split($columnName) as $character) {
            //  determine ASCII value of current character and substract with that one from letter "a"
            $characterNumberValue = ord($character) - $aAsciiValue;
    
            //  through iteration and multiplying we finally get the previous letters' values on base 26
            //  then we just add the current character's number value
            $columnNumber = $columnNumber * 26 + $characterNumberValue;
        }
    
        //  return the result
        return $columnNumber;
    }
    

    Of course the script can be shortened a little by just combining some stuff into one line of code within the foreach loop:

    //  …
    $columnNumber = $columnNumber * 26 + ord($character) - ord('a') + 1;
    //  …
    

提交回复
热议问题