码迷,mamicode.com
首页 > 编程语言 > 详细

171. Excel Sheet Column Number Leetcode Python

时间:2015-02-15 09:26:19      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:leetcode   递归   excel   python   

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 
Credits:

Special thanks to @ts for adding this problem and creating all test cases.


这题可以当作求26进制数来做。 可以用iterative的方法也可以用递归的方法来做


iterative:

class Solution:
    # @param s, a string
    # @return an integer
    def titleToNumber(self, s):
        result=0
        n=len(s)
        for i in range(n):
            result=result*26+ord(s[i])-64
        return result

recursive:

class Solution:
    # @param s, a string
    # @return an integer
    def titleToNumber(self, s):
        if len(s)==1:
            return ord(s)-64
        return ord(s[-1])-64+26*self.titleToNumber(s[:-1])

总体来说第一种方法速度比第二种要快。

171. Excel Sheet Column Number Leetcode Python

标签:leetcode   递归   excel   python   

原文地址:http://blog.csdn.net/hyperbolechi/article/details/43828957

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!