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
我想复杂了,下面是我的代码
1 class Solution { 2 public: 3 string convertToTitle(int n) { 4 map<int, string> m; 5 vector<string> vet(1, ""); 6 string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 7 for (int i = 1; i <= 26; i++) 8 { 9 string s = ""; 10 s = str[i - 1]; 11 vet.push_back(s); 12 13 } 14 15 for (int i = 0; i <= 26; i++) 16 { 17 m.insert(pair<int, string>(i, vet[i])); 18 } 19 cout<<m[26]<<endl; 20 stack<int> sta; 21 string str1 = ""; 22 while (n) 23 { 24 if(n<=26) 25 { 26 sta.push(n); 27 break; 28 } 29 if(n%26==0) 30 { 31 sta.push(26); 32 n=n/26-1; 33 } 34 else 35 {sta.push(n%26); 36 n=n/26; 37 } 38 } 39 while(sta.size()) 40 { 41 str1+=m[sta.top()]; 42 sta.pop(); 43 } 44 return str1; 45 } 46 };
我看别人提交的代码:
1 class Solution { 2 public: 3 string convertToTitle(int n) { 4 string ret(""); 5 if (n <= 0) 6 return ret; 7 8 while (n) { 9 --n; 10 ret += string(1, ((n) % 26) + 'A'); 11 n /= 26; 12 } 13 reverse(ret.begin(), ret.end()); 14 return ret; 15 } 16 };