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题意:26个英文字母分别表示1--26,则请把数字转换为字母表示。
思路:用数字n对26取模,若不等零,直接插入对应字符,若等零,插入Z并把数n减小26;n /= 26;熟练string类的insert函数的使用。
class Solution {
public:
string convertToTitle(int n) {
char ch[26];
ch[0] = 'Z';
for (int i = 1; i < 27; i++)
ch[i] = 'A' + i-1;
string s;
while (n){
int a = n % 26;
if (a == 0){
s.insert(s.begin(), 'Z');
n -= 26;
}
else{
s.insert(s.begin(), ch[a]);
}
n /= 26;
}
return s;
}
};