Description

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
...

Example 1:

Input: 1
Output: "A"

Example 2:

Input: 28
Output: "AB"

Example 3:

Input: 701
Output: "ZY"

分析

题目的意思是:把十进制的数转换成excel的列标题

  • 这道题目比较简单的进制转换问题。重点看看代码二的奇妙解法。

代码一

class Solution {
public:
string convertToTitle(int n) {
string res;
while(n){
if(n%26==0){
res.push_back('Z');
n=n/26;
n--;
if(!n){
break;
}
}else{
res.push_back(n%26+'A'-1);
n=n/26;
}

}

reverse(res.begin(),res.end());
return res;
}
};

代码二

   std::string str( "" );
while( n )
{
str = char( ( n - 1 ) % 26 + 'A') + str;
n = ( n - 1 )/26;
}
return str;

}

参考文献

​168. Excel Sheet Column Title​