您的位置:首页 > 其它

【leetcode】171. Excel Sheet Column Number

2016-06-05 11:23 429 查看
一、题目描述

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


c++代码(8ms)

思路:先找规律,找到规律后很容易就能写出代码

#include<iostream>
#include<string>
#include<math>
using namespace std;

class Solution {
public:
int titleToNumber(string s) {
int len=s.length();
int result = 0;
for(int i = 1; i<=len; i++)
result += pow(26, i-1) * (s[len-i] - 'A' + 1);
return result;
}
};

看了一下discuss,大神的代码如下:

java

int result = 0;
for (int i = 0; i < s.length(); result = result * 26 + (s.charAt(i) - 'A' + 1), i++);
return result;
c++
int result = 0;
for (int i = 0; i < s.size(); result = result * 26 + (s.at(i) - 'A' + 1), i++);
return result;

python
return reduce(lambda x, y : x * 26 + y, [ord(c) - 64 for c in list(s)])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: