[C++]LeetCode: 116 Excel Sheet Column Number (excel列坐标转数字)

来源:互联网 发布:豆瓣 知乎 贴吧 天涯 编辑:程序博客网 时间:2024/05/29 08:13

题目:

Related to question Excel Sheet Column Title

Given a column title as appear in an Excel sheet, return its corresponding column number.

For example:

    A -> 1    B -> 2    C -> 3    ...    Z -> 26    AA -> 27    AB -> 28 

思路:这道题和Excel Sheet Column Title和是对应的。这道题要求我们将excel中字母转成数字。观察规律,我们只需要将每个字母对应的数字求出来,迭代增加就可以,注意excel表格字母数字对应关系是26进制的。

Attention:

1. 26个英文字母转对应数字。s[i] - 'A' + 1

ans = (s[i] - 'A' + 1) + ans * 26;


复杂度:O(N)

AC Code:

class Solution {public:    int titleToNumber(string s) {        int ans = 0;        if(s.size() == 0) return ans;                for(int i = 0; i < s.size(); i++)        {            ans = (s[i] - 'A' + 1) + ans * 26;        }                return ans;    }};



0 0
原创粉丝点击