【LeetCode】168 & 171- Excel Sheet Column Title & Excel Sheet Column Number

168 - Excel Sheet Column Title

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 

Solution: 由于A->1,  计算s的末尾时需先减去1

 1 class Solution {
 2 public:
 3     string convertToTitle(int n) {
 4         string s;
 5         while(n){
 6             s =  (char)('A'+(n-1)%26)+s;
 7             n = (n-1)/26;
 8         }
 9         return s;
10     }
11 };

 

171 - Excel Sheet Column Number

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 

Solution:26进制转十进制,AAA=27*26+1
复制代码
1 class Solution {
2 public:
3     int titleToNumber(string s) {   //runtime:8ms
4         int ret=0;
5         for(int i=0;i<s.size();i++)ret = ret*26+s[i]-'A'+1;
6         return ret;
7     }
8 };
复制代码

 

posted @ 2015-08-06 23:05  irun  阅读(128)  评论(0编辑  收藏  举报