【easy】168. Excel Sheet Column Title 171. Excel Sheet Column Number

class Solution {
public:
    string convertToTitle(int n) {
        if (n == 0) {
            return "";
        }
        return convertToTitle((n - 1) / 26) + (char)((n - 1) % 26 + 'A');
    }
};

 

    A -> 1
    B -> 2
    C -> 3
    ...
    Z -> 26
    AA -> 27
    AB -> 28 
答案写法:
class Solution {
public:
    int titleToNumber(string s) {
        
        int sum = 0;  
        int tmp = 0;  
        for (int i = 0; i < s.length(); ++i) {  
            tmp = s[i] - 'A' + 1;  
            sum = 26 * sum + tmp;  
        }  
        return sum; 
  }
};

 


下面是自己写的:
class Solution {
public:
    int titleToNumber(string s) {
        int len = s.length();
        int num = 0;
        if (len == 1)
            num = s[0]-'A'+1;
        else{
            num += s[len-1]-'A'+1;
            int cal = 26;
            for (int i=len-2;i>=0;i--){
                num += (s[i]-'A'+1)*cal;
                cal *= 26;
            }

        }
        return num;
    }
};//从字符串到数字

 

posted @ 2018-01-23 11:29  Sherry_Yang  阅读(102)  评论(0编辑  收藏  举报