您的位置:首页 > 其它

leecode 解题总结:171. Excel Sheet Column Number

2017-02-21 11:21 197 查看
#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;
/*
问题:
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
AZ -> 52
BA -> 53

分析:此题是excel标题转化为数字。
之前数字转化为标题是:n-- , 'A' + n % 26 , n/=26
应该可以翻过来,获取高位字母'A',转化为字母 - 'A' + 1,然后乘以26
输入:
AAA
BA
AZ
Z
A
输出:
703
53
52
26
1

关键:
1 不断获取每一位字母,用该字母-'A'+1,然后乘以26的对应次方,累加即可
*/

class Solution {
public:
int titleToNumber(string s) {
if(s.empty())
{
return 0;
}
int len = s.length();
int result = 0;
int value = 0;
for(int i = 0; i < len ; i++)
{
value = s.at(i) - 'A' + 1;
result = result * 26 + value;
}
return result;
}
};

void process()
{
vector<int> nums;
string value;
int num;
Solution solution;
vector<int> result;
while(cin >> value )
{
num = solution.titleToNumber(value);
cout << num << endl;
}
}

int main(int argc , char* argv[])
{
process();
getchar();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: