标签:
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
提示:
此题考查的是对N进制数转10进制数的转换。
我自己的方法是从最低位开始转换,需要用到pow()函数:
class Solution { public: int titleToNumber(string s) { int result = 0; int length = s.length() - 1; for (int i = length; i >= 0; --i) { char c = s.at(i); result += (int(c)-64) * pow(26, length-i); } return result; } };
在论坛中看到了一种更好的方法,直接从最高位转换,代码比我的简洁不少:
class Solution { public: int titleToNumber(string s) { int len = s.size(); int sum = s[0] - 64; for (int i = 1;i < len; ++i){ sum = sum * 26 + int(s[i] - 64); } return sum; } };
【LeetCode】171. Excel Sheet Column Number
标签:
原文地址:http://www.cnblogs.com/jdneo/p/4741385.html