leetcode 168. Excel Sheet Column Title-表格栏目|进制转换

来源:互联网 发布:提花组织软件 编辑:程序博客网 时间:2024/06/06 01:05
原题链接:168. Excel Sheet Column Title

【思路-Java】

仿照十进制的做法,但有几点细节需要注意:

1. 为什么①处是(n - 1) % 26 + 'A',而不是 n % 26 + 64呢?这是因为 n = 26 时,求余的结果为0,就无法表示出 'Z',并且还需要注意一点,字符串是从右到左拼接的

2. 为什么②处是(n - 1) / 26,而不是 n / 26 呢?这是因为如果最后 n 刚好为26时,那么就不能接着运算了

这个数字转化为字母的过程与逆向字母转化为数字过程存在不同,所以还得考虑到细节处:

public class Solution {    public String convertToTitle(int n) {        StringBuilder sb = new StringBuilder();        while (n > 0) {            sb.insert(0, (char)((n - 1) % 26 + 'A'));  //①            n = (n - 1) / 26;  //②        }        return sb.toString();    }}
18 / 18 test cases passed. Runtime: 0 ms  Your runtime beats 6.39% of javasubmissions.

【思路-Python】

用到了 divmod 和 format 两个函数,对于 format 函数可能有人会有疑惑,为何不用  res = '%c%s' % (chr(base + r), res)  代替呢?其实也不是不可以,只是效率要低些,关于 format 不懂的人可以参考:python - 增强的格式化字符串format函数

class Solution(object):    def convertToTitle(self, n):        """        :type n: int        :rtype: str        """        res = ''        base = ord('A')        while n:            n, r = divmod(n - 1, 26)  //将(n-1)/26商赋值给 n,余数赋给 r            res = '{}{}'.format(chr(base + r), res)  //将 r 转化为字符后和 res 拼接        return res
18 / 18 test cases passed. Runtime: 44 ms  Your runtime beats 17.72% of pythonsubmissions.

1 0
原创粉丝点击