標籤:
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 = 1 * 26 ^ 0 -> A
...
26 = 26 * 26 ^ 0 -> Z
27 = 1 * 26 ^ 1 + 1 * 26 ^ 0 -> AA
28 = 1 * 26 ^ 1 + 2 * 26 ^ 0 -> AB
...
可以發現1對應‘A‘ , 2對應‘B‘,比如我們怎麼得到AB呢?首先我們對n % 26,那麼由數論知識,已知就得到2了,這個2就可以得到‘B‘,接下來n = n / 26, 即 28 / 26 = 1 * 26 ^ 0 + 0,直到n <= 0.顯然我們很容易得到了這個1,也就得到了‘A‘,將串連起來的字串反轉,也就是"AB"了。
注意:26怎麼處理呢?以及52又怎麼辦呢?那麼這裡我們只需要另外加個條件就行了:if(n % 26 == 0) 0對應的是‘Z‘.並且要n = n - 26,再進行後面 n = n / 26的處理。
比如 52 = 1 * 26 ^1 + 26 * 26 ^ 0,52對應的是AZ。首先52 % 26 = (1 * 26 ^ 1 + 26 * 26 ^ 0) % 26 = 0,所以我們輸出一個‘Z‘,如果不進行n = n - 26,去除掉最低位的個位元,那麼 52 / 26 = (1 * 26 ^ 0 + 1 * 26 ^ 0) = 2 * 26 ^ 0,那麼得到的就是2即‘B‘了,出錯。
1 class Solution { 2 public: 3 string convertToTitle(int n) { 4 string s = ""; 5 char c; 6 while(n >= 1){ 7 if(n % 26 == 0){ 8 n -= 26; 9 c = ‘Z‘;10 }11 else 12 c = ‘A‘ + (n % 26 - 1);13 s += c;14 n = n / 26;15 }16 reverse(s.begin(), s.end());17 return s;18 }19 };
也可以用遞迴的:
1 #include <iostream> 2 using namespace std; 3 void convertToTitle(int n){ 4 if(n <= 0) 5 return; 6 if(n % 26 == 0) 7 n = n - 26; 8 convertToTitle(n / 26); 9 if(n % 26 == 0){10 cout << ‘Z‘;11 } else {12 cout << (char)(‘A‘ + (n % 26) - 1);13 }14 }15 16 int main(){17 int n;18 while(cin >> n){19 convertToTitle(n);20 cout << endl;21 }22 return 0;23 }
Leetcode 168. Excel Sheet Column Title