標籤:
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