Excel Sheet Column Number 续

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 

python给出来的函数定义和参数如下

class Solution:
    # @param s, a string
    # @return an integer
    def titleToNumber(self, s):

既然前面C语言已经将过程弄清楚了,python就可以照葫芦画瓢了,但是关键是python如何打印ascii,先实验一把

>>> ord('A')
65
>>> ord('B')
66
>>> ord('AB')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found
>>> 

可以看到很容易的说,把C的流程搬过来,实现一边,提交

class Solution:
# @param s, a string
# @return an integer
    def titleToNumber(self, s):
        sum = 0
        for ch in s:
	    sum = sum * 26 + ord(ch) - 64
	return sum

结果毫不客气的Error

Submission Result: Runtime ErrorMore Details 

Runtime Error Message:	Line 8: IndentationError: unindent does not match any outer indentation level
Last executed input:	"A"

仔细看了看,好像意思对齐是不是有问题,火眼晶晶秒了秒,return好像多空了一格

重新提交试试

class Solution:
    # @param s, a string
    # @return an integer
    def titleToNumber(self, s):
        sum = 0
        for ch in s:
            sum = sum * 26 + ord(ch) - 64
        return sum

果然OK了

Submission Details
1000 / 1000 test cases passed.
Status: Accepted
Runtime: 78 ms

发表评论