LeetCode[Math]----Excel Sheet Column Title----Excel Sheet Column Number

来源:互联网 发布:手机短信淘宝链接 编辑:程序博客网 时间:2024/04/28 19:59

Excel Sheet Column Title

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

For example:

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

分析:

给一个正整数,返回对应的Excel中列的表示。这种表示是用字母A-Z来表示的,以26为进制。

类比十进制,我们递归的来处理给定的数字num。首先,如果num是属于1-26,那么直接返回这个数字对应的字符即可;如果它大于26,那么这个num的表示char可以表示为两部分prefix和endfix,endfix为num%26对应的字符表示,而prefix为num/26的字符表示。

对于26进制,在当num可以被26整除时,余数为0,而此时的endfix表示应该为Z,而prefix应为(num/26)-1对应的字符。


代码为:

class Solution(object):    def convertToTitle(self, n):        """        :type n: int        :rtype: str        """        if 1 <= n <= 26:            return chr(64 + n)        if n % 26 == 0:            return self.convertToTitle((n / 26) - 1) + 'Z'        return self.convertToTitle(n / 26) + self.convertToTitle(n % 26)

非递归代码为:

class Solution(object):    def convertToTitle(self, n):        """        :type n: int        :rtype: str        """        char = ''        while n:            char = chr((n-1) % 26 + 65) + char            n = (n-1) / 26        return char


--------------------------------------------------------------------------------------

分割线,下面是上面一题的逆转换。

Excel Sheet Column Number

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 


分析:

给定相应的字符表示,还原出对应的数字。

原串的表示仍然是通过26进制生成的,类似于10进制,数字每增加一位x,表示值增加了x*(10^y),y为x在数字中的第y位(从0开始)。比如十进制abc=a*10^2 + b*10^1 + c*10^0。同样的给定26进制表示的字符串如ABC=A*26^2 + B*26^1 + C*26^0=1*26^2 + 2*26^1 + 3*26^0=731.


对应的代码为:

class Solution(object):    def titleToNumber(self, s):        """        :type s: str        :rtype: int        """        if len(s) == 1:            return ord(s) - 64        return self.titleToNumber(s[-1]) + self.titleToNumber(s[:-1]) * 26

非递归代码为:

class Solution(object):    def titleToNumber(self, s):        """        :type s: str        :rtype: int        """        num = 0        while s:            num = num * 26 + ord(s[0]) - 64            s = s[1:]        return num

0 0