【leetcode】168. Excel Sheet Column Title(Python & C++)

来源:互联网 发布:win7最大优化 编辑:程序博客网 时间:2024/05/28 11:28

168. Excel Sheet Column Title

题目链接

168.1 题目描述:

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

For example:

1 -> A2 -> B3 -> C...26 -> Z27 -> AA28 -> AB 

168.2 解题思路:

  1. 思路一:类似于十进制转二进制。只不过这里是26进制,但是又和标准的26进制不同,这里不存在0位,也就是只有1-26,即A-Z。初始化字符串s=”“。循环n大于0,首先n对26取余,d=n%26,n=n/26,如果d不为0的话,则直接将d+64转化为字符加在字符串s前面。如果d为0,则d=26,且n–。因为当n是26的倍数时,并没有进位,还是Z。最后返回s即可。例如,n=26,并不是A0,而是Z。

  2. 思路二:等同于思路一,写法优化。在进入循环n大于0时,首先就对n=n-1。处理n是26的倍数这种情况。

168.3 C++代码:

1、思路一代码(0ms):

class Solution131 {public:    string convertToTitle(int n) {        string s = "";        if (n < 1)            return s;        int i = 1;        while (n > 0)        {            int d = n % 26;            n = n / 26;            if (d == 0)            {                d = 26;                n--;            }            char c = d + 64;            s = c + s;        }        return s;    }};

2、思路二代码(0ms)

class Solution131_1{public:    string convertToTitle(int n) {        string s = "";        if (n < 1)            return s;        int i = 1;        while (n > 0)        {            n = n - 1;            int d = n % 26;            n = n / 26;            char c = d + 65;            s = c + s;        }        return s;    }};

168.4 Python代码:

1、思路一代码(28ms)

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

2、思路二代码(38ms)

class Solution1(object):    def convertToTitle(self, n):        """        :type n: int        :rtype: str        """        s=""        if n<1:            return s        while n>0:            n=n-1            d=n%26            n=n/26            s=chr(65+d)+s        return s