C++ 中的 Excel 工作表列标题
c++server side programmingprogramming更新于 2024/11/7 13:12:00
假设我们有一个正整数;我们必须找到其在 Excel 工作表中对应的列标题。因此 [1 : A], [2 : B], [26 : Z], [27 : AA], [28 : AB] 等。
因此,如果输入为 28,则输出为 AB。
为了解决这个问题,我们将遵循以下步骤 −
当 n 非零时,执行 −
n := n - 1
res := res + n mod 26 + 'A' 的 ASCII
n := n / 26
反转数组 res
返回 res
示例
让我们看下面的实现,以便更好地理解 −
#include <bits/stdc++.h> using namespace std; class Solution { public: string convertToTitle(int n) { string res; while(n){ res += (--n)%26 + 'A'; n /= 26; } reverse(res.begin(), res.end()); return res; } }; main(){ Solution ob; cout << (ob.convertToTitle(30)); }
输入
30
输出
AD