[Leetcode] 171. Excel Sheet Column Number 解题报告

xiaoxiao2021-02-28  81

题目:

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

思路:

从最右边向最左边扫描。最右边的基数是1,依次向左基数以26倍增大。最后把结果累加起来即可。

代码:

class Solution { public: int titleToNumber(string s) { if (s.length() == 0) { return 0; } int ret = 0, radix = 1; for (int i = s.length() - 1; i >=0; --i) { int value = s[i] - 'A' + 1; ret += radix * value; radix *= 26; } return ret; } };

转载请注明原文地址: https://www.6miu.com/read-77293.html

最新回复(0)