【leetcode】171. Excel Sheet Column Number

一、题目描述

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
#include
#include
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)])



你可能感兴趣的:(【leetcode】171. Excel Sheet Column Number)