leetcode 171. Excel Sheet Column Number(C语言)

来源:互联网 发布:淘宝新开店铺 编辑:程序博客网 时间:2024/06/07 06:56

第四天


贴原题:

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 

Credits:
Special thanks to @ts for adding this problem and creating all test cases.


解读与分析:

本题其实就是就是让写一个26进制,这一点我在读完题之后就发现了。然而写程序的时候完全凭脑子想,思维有点混乱,写了一个多小时才解出来,很难受……

因为A的ASCII码是65,那么A-64=1。然后把ABCD……这样等价于1,2,3,4……相应的,Z等价于26,满26进1。

接下来就是计算各位的权重,再相加就行了。看不懂的话,看一下注释吧……

贴我的C代码:

int titleToNumber(char* s) {    int len=strlen(s);    int output=0;    for(int i=0; i<len; i++)    {        int temp=*(s+i)-64;//临时变量存放当前位上的值        for(int j=0; j<len-i-1; j++)        {            temp*=26;//当前位的值乘上此位的权重,即乘以26的乘方        }        output+=temp;//把计算的权重值逐位相加    }    return output;}



原创粉丝点击