168. Excel Sheet Column Title
和171题是一个类型的,参考[LeetCode]171. Excel Sheet Column Number
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
代码如下:
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
string convertToTitle(int n) {
string s = "";
if(n == 0)
return s;
else
//return convertToTitle(n/26) + char((n-1)%26+'A');//n=26时 return AZ 错误
return convertToTitle((n-1)/26) + char((n-1)%26+'A');
}
};
int main()
{
Solution a;
int n;
cin >> n;
cout << a.convertToTitle(n) << endl;
return 0;
}
注意:
- 递归时convertToTitle((n-1)/26),n一定要减1,否则会发生错误
本文介绍了一种将Excel表格中的列号转换为对应列标题的方法,并提供了一个使用C++实现的具体实例。通过递归算法,可以将任意正整数(列号)转换为其对应的字母序列(列标题),例如28对应的列标题为AB。
970

被折叠的 条评论
为什么被折叠?



