标签:
leetcode - Excel Sheet Column Number
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 class Solution { 2 public: 3 int titleToNumber(string s) { 4 string::iterator it = s.end()-1; 5 int i = 0; 6 int num = 0; 7 while(i<s.size()){ 8 num = num + (*it - ‘A‘ + 1) * pow(26,i); 9 it--; 10 i++; 11 } 12 return num; 13 } 14 };
比较简单了。 但是写的不够简洁
class Solution { public: int titleToNumber(string s) { int ret = 0; for(int i = 0; i < s.size(); i ++) ret = ret*26 + (s[i]-‘A‘+1); return ret; } };
这个写的很好,没有用pow,也不用iterator,本身问题就很简单。
累计的时候每次都把原来的累加和乘以进制即可(乘以26)。
leetcode - Excel Sheet Column Number
标签:
原文地址:http://www.cnblogs.com/shnj/p/4501094.html