#Leetcode# 168. Excel Sheet Column Title
阿新 • • 發佈:2018-11-29
https://leetcode.com/problems/excel-sheet-column-title/
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"
Example 2:
Input: 28 Output: "AB"
Example 3:
Input: 701 Output: "ZY"
程式碼:
class Solution { public: string convertToTitle(int n) { string ans; int cnt = 0; while(n) { if(n % 26 == 0) { ans[cnt ++] = 'Z'; n -= 26; } else { ans[cnt ++] = 'A' - 1 + (n % 26); n -= n % 26; } n /= 26; } for(int i = 0; i < cnt / 2; i ++) swap(ans[i], ans[cnt - i - 1]); return ans; } };
每次 $n$ 要減去 $n % 26$ 然後再 $n / 26$ 還有要注意的就是當 $n$ 可以被 $26$ 整除的時候要特別寫一下 唉 這個題看了半天