Sunday, January 18, 2015

[Leetcode] Excel Sheet Column Number

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:

We know a number could be represented as binary, octal, decimal or hexadecimal. So what if we want to represent a number with 26 as base? We could represent 1 as A, 2 as B and Z as 26 which is exactly how an Excel column title works. 

It is pretty strait forward to convert a decimal represented string to a number, eg "123" = 1*100 + 2*10 + 3. Well, it is almost exactly the same for 26 based number as well, as the following code shows. 




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

No comments:

Post a Comment