【leetcode】excel

来源:互联网 发布:在线直播平台源码 编辑:程序博客网 时间:2024/06/06 01:27

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

分析:可以当作是进制转换。先确定字符串的位数,然后从低位到高位,转换到相对应的数字,然后累加。

class Solution {public:    int titleToNumber(string s) {    int digits=s.size();int res=0;for (int i=digits-1;i>=0;i--){res=res+(s[i]-'A'+1)*(double)pow((double)26,digits-i-1);}return res;    }};



类似的:

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

    1 -> A    2 -> B    3 -> C    ...    26 -> Z    27 -> AA    28 -> AB 
分析:注意每一位是从1开始,而不是0,因此与数字上的进制转换有所差别。要先减一处理。

class Solution {public:    string convertToTitle(int n) {<span style="white-space:pre"></span>if (n==1){return "A";}int digits;digits=(double)log((double)((double)25/26*(n-1)+1))/(double)log((double)26)+1;string re;re.resize(digits);for (int i=digits-1;i>=0;){int t=(n-1)%26+1;re[i--]='A'+t-1;n=(n-((n-1)%26+1))/26;}return re;    }};

出现的问题:

1、确定位数时,应根据等比数列求和的公式倒推回来。当n较大时,可能*25会溢出,所以先算25/26,并强制转换为double,不然就是int了。

2、由于每位都是从1开始,因此做进制转换时,先减一,如 (n-1)%26+1;

0 0
原创粉丝点击