###### tags: `Leetcode` `easy` `string` `python` `c++` # 168. Excel Sheet Column Title ## [題目來源:] https://leetcode.com/problems/excel-sheet-column-title/ ## 題目: Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet. For example: ``` A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ```  #### [圖片來源:] https://leetcode.com/problems/excel-sheet-column-title/ ## 解題想法: 兄弟題目:參考 [171. Excel Sheet Column Number](/VYX6P02LTxScpXZD132rQA) * 此題為數字轉字母 視為26進位,逐一求餘數,最終再將結果reverse ## Python: ``` python= class Solution(object): def convertToTitle(self, columnNumber): """ :type columnNumber: int :rtype: str """ dic="ABCDEFGHIJKLMNOPQRSTUVWXYZ" res=[] while columnNumber: #-1: 若input = 1 則m=0 ->>>> dic[0]-> 得到A pos=(columnNumber-1)%26 res.append(dic[pos]) columnNumber=(columnNumber-1)//26 res.reverse() return "".join(res) if __name__ == '__main__': result = Solution() columnNumber = 28 ans = result.convertToTitle(columnNumber) print(ans) ``` ## C++: ``` cpp= #include<iostream> #include<algorithm> using namespace std; class Solution{ public: string convertToTitle(int columnNumber){ string dic="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string res; while (columnNumber>0){ int pos = (columnNumber-1)%26; res+=dic[pos]; columnNumber= (columnNumber-1)/26; } //<algorithm> reverse(res.begin(),res.end()); return string(res); } }; int main(){ Solution res; int columnNumber = 701; cout<<res.convertToTitle(columnNumber)<<endl; return 0; } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up