leetcode NO.171 Excel表列序號 (python實現)


來源

https://leetcode-cn.com/problems/excel-sheet-column-number/description/

題目描述

給定一個Excel表格中的列名稱,返回其相應的列序號。

例如,

    A -> 1
    B -> 2
    C -> 3
    ...
    Z -> 26
    AA -> 27
    AB -> 28 
    ...
示例 1:

輸入: "A"
輸出: 1
示例 2:

輸入: "AB"
輸出: 28
示例 3:

輸入: "ZY"
輸出: 701

代碼實現

class Solution(object):
    def titleToNumber(self, s):
        """
        :type s: str
        :rtype: int
        """
        result = 0 
        for letter in s:
            result = result * 26 + ord(letter) - ord('A') + 1
        return result

拓展

  • ord(c)
    Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().

  • chr(i)
    Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. This is the inverse of ord().The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be raised if i is outside that range.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM