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 res18 / 18 test cases passed. Runtime: 44 ms Your runtime beats 17.72% of pythonsubmissions.
1 0
- leetcode 168. Excel Sheet Column Title-表格栏目|进制转换
- 168.leetcode Excel Sheet Column Title(easy)[进制转换]
- LeetCode 168. Excel Sheet Column Title(EXCEL栏目)
- 【leetcode 进制转换】Excel Sheet Column Title
- [LeetCode]168. Excel Sheet Column Title(Excel表格列标题)
- Excel Sheet Column Title 进制转换
- leetcode 168. Excel Sheet Column Title | 进制转化
- [LeetCode]168.Excel Sheet Column Title
- 168. Excel Sheet Column Title Leetcode Python
- LeetCode 168. Excel Sheet Column Title
- 【LeetCode】168.Excel Sheet Column Title
- [leetcode] 168.Excel Sheet Column Title
- [LeetCode]168. Excel Sheet Column Title
- 168. Excel Sheet Column Title LeetCode
- leetcode 168. Excel Sheet Column Title
- Leetcode: 168. Excel Sheet Column Title(JAVA)
- LeetCode *** 168. Excel Sheet Column Title
- leetcode-168. Excel Sheet Column Title
- ACM: 简单排序题 poj 2231 动动脑…
- 动态规划: 装配线调度问题 (算法导…
- ACM: 矩阵链乘 动态规划题 poj 165…
- 深度优先搜索(deep first search)
- ACM: 矩阵快速幂运算 数论题 poj 3…
- leetcode 168. Excel Sheet Column Title-表格栏目|进制转换
- ACM: 经过K条边的最短路 图论题 po…
- 1019
- ACM: 矩阵建模 数论题 poj 3735 (…
- ACM: 二分又二分 数论题 poj 3233
- SeaJS与RequireJS最大的区别
- ACM: 矩阵变形题 数论题 poj 3150
- 学习心得:《十个利用矩阵乘法解决…
- 计算几何:正多边形的滚动与旋轮线…