LeetCode 171 Excel Sheet Column Number (Number of columns in Excel)
Translation
Returns the correct number of rows for a list title that appears in an Excel table. Example: A-> 1 B-> 2 C-> 3... Z-> 26 AA-> 27 AB-> 28
Original
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
Analysis
With the experience of the previous question, it is much easier this time. The meaning can also be understood, that is, the characters on the left of the above instance are converted to numbers on the right.
The following is the blog of the previous question. I gave an example of hexadecimal conversion, but I didn't make it very clear. I 'd like to fully explain it in this question, please continue.
I believe that with this example, you can understand it in seconds.
Then I wrote the following code:
#include
using namespace std;int exponent(int x, int y) { int answer = 1; for(int i = 0; i < y; ++ i) { answer *= x; } return answer;}int titleToNumber(string s) { int n = 0, len = s.length(); for(int i = 0; i < s.length(); ++ i) { char c = s[i]; int chara = c - 'A' + 1; n += chara * exponent(26, len - 1 - i); } return n;}int main() { cout<
The output result is
704
This is correct, and I changed it to the following code:
#include #include using namespace std;int titleToNumber(string s) { int n = 0, len = s.length(); for(int i = 0; i < s.length(); ++ i) { char c = s[i]; int chara = c - 'A' + 1; n += chara * pow(26, len - 1 - i); } return n;}int main() { cout<
The output is:
703
So I wondered, And then I switched from CodeBlocks to Visual Studio, which became 704, and 704 was correct.
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxwPjxjb2RlIGNsYXNzPQ = "hljs cpp"> In CB, change the code:
n += chara * (int)pow(26.0, len - 1 - i);
The result is 702.
I hope you can leave a message below to tell me what the problem is ......
Code
class Solution {public: int titleToNumber(string s) { int n = 0, len = s.length(); for (int i = 0; i < s.length(); ++i) { char c = s[i]; int chara = c - 'A' + 1; n += chara * pow(26, len - 1 - i); } return n; }};