Excel Sheet Column Title
讲数字转为字母’A’到’Z’表示,对应关系如图
思路:
本质上是将10尽职转为26进制,不同的是模的结果从 [0:25] 变为 [1:26]
假设 1<=n%26<=26 ,那么 0<=(n−1)%26<=25 ,所以可以每次取模时先减一
代码如下
class Solution {
public:
string convertToTitle(int n) {
string res("");
do
{
res.append(1, 'A' + (n - 1) % 26);
/* n - 1的目的是解决模结果为0的情况 */
n = (n - 1) / 26;
}while(n);
std::reverse(res.begin(), res.end());
return res;
}
};
Excel Sheet Column Number
上一题的逆序,直接转成26进制即可
代码如下
class Solution {
public:
int titleToNumber(string s) {
return std::accumulate(s.begin(), s.end(), 0,
[](auto n, auto value)
{
return n * 26 + (value - 'A' + 1);
}
);
}
};