#leetcode#168 171 Excel Sheet Column Title 与 Excel Sheet Column Number

来源:互联网 发布:java mysql 批处理 编辑:程序博客网 时间:2024/05/22 01:30

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 

26进制转化

注意开始位置为1


一直除,取余


class Solution {public:    string convertToTitle(int n) {        string array[26]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};        string answer="";        string each_digit="";        while(n!=0)        {            int digit=n%26;            if(digit==0) digit=26;            each_digit=array[digit-1];            answer=each_digit+answer;            n=(n-1)/26;        }        return answer;    }};


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 


反过来

class Solution {
public:
    int titleToNumber(string s) {
        int n=s.size();
        int i;
        int ans=0;
        for(i=0;i<n;i++)
        {
            int j=n-i-1;
            int a=1;
            for(int k=0;k<j;k++)
            {
                a=26*a;
            }
            int b=s[i]-'A'+1;
            ans=ans+b*a;
        }
        return ans;
    }
};






0 0
原创粉丝点击