本文主要是介绍LeetCode 题解(215) : Excel Sheet Column Title,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
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
题解:
想明白了就容易了。 求base-26的表达式,用A~Z表示。
由低位向高位计算。计算每一位的计算公式为: 'A' + (n - 1) % 26
n = (n - 1) / 26
C++版:
class Solution {
public:string convertToTitle(int n) {string result = "";while(n > 0) {result = (char)('A' + (n - 1) % 26) + result;n = (n - 1) / 26;}return result;}
};
Java版:
public class Solution {public String convertToTitle(int n) {StringBuffer sb = new StringBuffer();while(n > 0) {sb.insert(0, (char)('A' + (n - 1) % 26));n = (n - 1) / 26;}return sb.toString();}
}
Python版:
class Solution(object):def convertToTitle(self, n):""":type n: int:rtype: str"""result = ""while n > 0:result = chr(ord("A") + (n - 1) % 26) + resultn = (n - 1) / 26return result
这篇关于LeetCode 题解(215) : Excel Sheet Column Title的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!