[leetcode]168. Excel Sheet Column Title
阿新 • • 發佈:2018-12-04
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 ...
Example 1:
Input: 1 Output: "A"
分析:
給定一個整數,返回相應的字母組合。相當於26進位制,若不是26的整數倍,從低位往高位求,每進一位,則把原數縮小26倍,再對26取餘,之後減去餘數,再縮小26倍,最後只需將整個字串翻轉一下即可;如果是26的整數倍的話,直接加倍數個‘Z’即可。
class Solution { public: string convertToTitle(int n) { string res = ""; while (n) { if (n % 26 == 0) { res += 'Z'; n -= 26; } else { res += n % 26 - 1 + 'A'; n -= n % 26; } n /= 26; } reverse(res.begin(), res.end()); return res; } };