###### tags: `Leetcode` `easy` `string` `python` `c++` # 171. Excel Sheet Column Number ## [題目來源:] https://leetcode.com/problems/excel-sheet-column-number/ ## 題目: Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number. For example: ``` A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... ```  #### [圖片來源]: https://leetcode.com/problems/excel-sheet-column-number/ ## 解題思路: 兄弟題目:參考 [168. Excel Sheet Column Title](/rt05Jg7TSwKYzNMFxfzY1Q) * 此題為字母轉數字: 從頭逐一累加*26 * 注意 * python: **ord(' A ')=65** * c++: **' 字母 '-'A'+1** ## Python: ``` python= class Solution(object): def titleToNumber(self, columnTitle): """ :type columnTitle: str :rtype: int """ #ord('A')=65 res=0 for i in range(len(columnTitle)): res*=26 res+=ord(columnTitle[i])-64 return res if __name__ == '__main__': res = Solution() columnTitle = "AB" print(res.titleToNumber(columnTitle)) ``` ## C++: ``` cpp= #include<iostream> using namespace std; class Solution { public: int titleToNumber(string columnTitle) { int res=0; //使用萬用auto for (auto val: columnTitle){ res*=26; res+= (val-64); } return res; /* // sol2: for (int i=0; i<columnTitle.size(); i++){ res*=26; res+= columnTitle[i]-'A'+1; } */ } }; int main(){ Solution res; string columnTitle="AB"; int ans=res.titleToNumber(columnTitle); cout<<ans<<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