168 Excel Sheet Column Title

來源:互聯網
上載者:User

標籤:

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 

題目的意思大概是這樣的意思大概是這樣的,給定一個正數,返回在EXCEL表中的欄位標題
其實從栗子中可以看出來其實就是一個十進位轉26進位的問題
下面給出我的解決方案:
方案一:
採用迴圈的方法,每次得到餘數轉成對應的字元的形式,添加到字串中最後將這個字串逆置
 1 class Solution { 2 public: 3    string convertToTitle(int n) { 4           if(n<1) return ""; 5           else{ 6           string result=""; 7           char ch; 8           while(n){ 9             n--;10             ch = n%26+‘A‘;11             result+=ch;12             n/=26;13           }14           reverse(result.begin(), result.end());15           return result;16           }17     }18 };

值得注意的是其中n--;這個是在n是26的倍數的時候出現的問題,如果是ch=n%26+64會出現‘@‘的情況

第二種方案:

    採用遞迴的方式

 1 #include<iostream> 2 #include<string> 3 using namespace std; 4 class Solution { 5 public: 6     string convertToTitle(int n) { 7           static string s=""; 8           int p=0; 9           if(n){10              n--;11              p = n%26;12              convertToTitle(n/26);13              if(p)14                 s+=(char)(p+‘A‘);15           }16           return s;17     }18 };19 int main(){20    Solution *s = new Solution;21    //cout<<s->convertToTitle(28)<<endl;22    cout<<s->convertToTitle(26);23     return 0;24 }

由於使用了static關鍵字,函數在連續調用的時候會出現問題所以沒有通過AC,只是提供了一種思路。

第一種方案是可以AC的~

168 Excel Sheet Column Title

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.