Leetcode 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 

思路:
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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.