[LeetCode] 168. Excel Sheet Column Title 求Excel表列名称
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
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases.
给一个正整数,返回Excel表中对应的列标题。
解法:由例子可以看出是按26个字母循环,相当于10进制和26进制转换,所以可以对26取整取余。每有一个26就加一个A,剩下的余数对应相应的字母。
Python:
1 2 3 4 5 6 7 8 9 | class Solution( object ): def convertToTitle( self , n): result, dvd = "", n while dvd: result + = chr ((dvd - 1 ) % 26 + ord ( 'A' )) dvd = (dvd - 1 ) / 26 return result[:: - 1 ] |
C++:
1 2 3 4 5 6 7 8 9 10 11 | class Solution { public : string convertToTitle( int n) { string res; while (n) { res += --n % 26 + 'A' ; n /= 26; } return string(res.rbegin(), res.rend()); } }; |
类似题目:
[LeetCode] 171. Excel Sheet Column Number 求Excel表列序号
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步