C++ 中 Excel 表格列標題


假設我們有一個正整數;我們必須找到其作為 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

更新於: 10-6-2020

760 次瀏覽

開啟 事業

透過完成課程,獲得認證

開始學習
廣告
© . All rights reserved.