168. Excel Sheet Column Title [easy] (Python)
2016-05-14 16:22
816 查看
题目链接
https://leetcode.com/problems/excel-sheet-column-title/题目原文
Given a positive integer, return its corresponding column title as appear in an Excel sheet.给定一个正整数,返回其在Excel表格中作为列序号时对应的列标题。
For example:
1 -> A
2 -> B
3 -> C
…
26 -> Z
27 -> AA
28 -> AB
题目翻译
给定一个正整数,返回其在Excel表格中作为列序号时对应的列标题。比如:1 -> A
2 -> B
3 -> C
…
26 -> Z
27 -> AA
28 -> AB
思路方法
首先,我们要知道Excel里这个对应关系是什么样的。从A-Z对应1-26,当列标题进一位变成AA时,列对应的数字变成27。所以这个题本质上是一个10进制转26进制的问题,不过A对应的是1而不是0,要注意。思路一
用处理进制转换的一般思路,重复取模和除法即可。但是注意由于A对应1,所以Z之后是AA,这个转换不同于一般的进制转换。代码
class Solution(object): def convertToTitle(self, n): """ :type n: int :rtype: str """ res = '' while n: res = chr((n-1)%26 + 65) + res n = (n-1) / 26 return res
思路二
与上面的思路类似,但采用递归来实现。代码
class Solution(object): def convertToTitle(self, n): """ :type n: int :rtype: str """ if n == 0: return '' return self.convertToTitle((n-1)/26) + chr((n-1)%26 + 65)
相关问题:171. Excel Sheet Column Number
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:/article/11857830.html
相关文章推荐
- python爬取51job中hr的邮箱
- 171. Excel Sheet Column Number [easy] (Python)
- Python函数作用域的查找顺序
- 242. Valid Anagram [easy] (Python)
- python02-数据类型与字符串编码
- python程序生成平均脸
- 第二章 Python简介
- Python基础——准备工作
- 判断一个数是不是3的幂——Power of three?
- python学习笔记(arange函数与linspace函数)
- python eval()
- python中如果函数后面有多于一个括号是怎么回事?
- 第三节,入门知识和windows系统安装python环境
- Python实战_0_第一周_第一节练习项目:动手做自己的网页
- python添加django插件
- Python:递归和装饰器
- Guido von Rossum - i wrote python
- Python六大开源框架对比:Web2py略胜一筹
- Python matplotlib pyplot中title() xlabel() ylabel()无法显示在中文(方框乱码)的解决办法
- python函数中参数是如何传递的?