美文网首页
Q171 Excel Sheet Column Number

Q171 Excel Sheet Column Number

作者: 牛奶芝麻 | 来源:发表于2018-02-28 16:34 被阅读7次

    Related to question Excel Sheet Column Title

    Given a column title as appear in an Excel sheet, return its corresponding column number.

    For example:
     A -> 1
     B -> 2
     C -> 3
     ...
     Z -> 26
     AA -> 27
     AB -> 28 
    
    解题思路:

    参考题目: Q168 Excel Sheet Column Title

    此题与 Q168 Excel Sheet Column Title 刚好相反,从低位到高位累加即可。

    Python实现:
    class Solution(object):
        def titleToNumber(self, s):
            """
            :type s: str
            :rtype: int
            """
            lens = len(s)
            if lens == 0:
                return 0
            ans, p, i = 0, 0, lens - 1
            while i >= 0:
                ans += (ord(s[i]) - ord('A') + 1) * pow(26, p)
                p += 1; i -= 1
            return ans
    
    a = 'BA'
    b = 'ZZ'
    c = Solution()
    print(c.titleToNumber(a))  # 53
    print(c.titleToNumber(b))  # 702
    

    相关文章

      网友评论

          本文标题:Q171 Excel Sheet Column Number

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