力扣168. Excel表列名称(进制转换)
https://leetcode-cn.com/problems/excel-sheet-column-title/
给定一个正整数,返回它在 Excel 表中相对应的列名称。
例如,
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
...
示例 1:
输入: 1
输出: "A"
示例 2:
输入: 28
输出: "AB"
示例 3:
输入: 701
输出: "ZY"
注意对应关系中是从1开始的,因此我们预先对n做处理,然后进行%26和/26
关键点:每次计算前先减 1
#include "stdafx.h"
#include<string>
#include <iostream>
using namespace std;
class Solution
{
public:
string convertToTitle(int n)
{
string str;
while (n)
{
n--;
str = (char)(n % 26 + 65) + str;
n = n / 26;
}
return str;
}
};
int main()
{
Solution s;
auto result = s.convertToTitle(701);
for (int i = 0; i < result.size(); i++)
{
cout << result[i] << '\t';
}
return 0;
}