美文网首页Leetcode题解-PHP版
Leetcode PHP题解--D93 171. Excel S

Leetcode PHP题解--D93 171. Excel S

作者: skys215 | 来源:发表于2019-06-24 10:00 被阅读0次

    D93 171. Excel Sheet Column Number

    题目链接

    171. Excel Sheet Column Number

    题目分析

    用过Excel的网友应该知道,它从A列开始到Z列,Z列之后是AA列,AB列,以此类推。

    现在给定一个列名,需要转换成数字。

    思路

    这题的本质是26进制到十进制的转换。

    首先,需要把A~Z转换成1到26。

    之后,从最低位开始,每一位为26的n次方。

    最终代码

    <?php
    class Solution {
    
        /**
         * @param String $s
         * @return Integer
         */
        function titleToNumber($s) {
            $len = strlen($s);
            $s = str_split($s);
            $number = 0;
            while($len){
                $number += (ord(array_shift($s))-ord('A')+1)*pow(26,--$len);
            }
            return $number;
        }
    }
    

    若觉得本文章对你有用,欢迎用爱发电资助。

    相关文章

      网友评论

        本文标题:Leetcode PHP题解--D93 171. Excel S

        本文链接:https://www.haomeiwen.com/subject/qyqnqctx.html