# A 8ms C++ Solution

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

• An alternative solution: from left to right to calculate the value of string s. e.g:
"AB" = ('A'-'A'+1) * 26 + ('A'-'B'+1)

``````class Solution {
public:
int titleToNumber(string s) {
int result = 0;
for (auto c : s) {
result = result*26 + (c - 'A' + 1);
}
return result;
}
};
``````

• @tianhongbo1 according to your equation, the ''AB'' string equals 26. Its actual value is 28. Please correct for this

• @yuming.wei Using "pow" method every time in the loop is making your solution slow. You can easily avoid it.

Here's my 3ms C++ code.

``````int titleToNumber(string s) {
int cnum = 0;
for(int i = 0; i < s.length(); i++){
cnum *= 26;
cnum += s[i] - 'A' + 1;
}
return cnum;
}
``````

• @ddeveshh the same to you,but mine is 6ms ,why

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.