码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] Excel Sheet Column Title & Excel Sheet Column Number

时间:2015-01-05 10:47:31      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

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 

思路:

10进制转26进制 。先求低位再求高位,与10进制转2进制一样。

题解:

技术分享
class Solution {
public:
    string convertToTitle(int n) {
        string res;
        while(n) {
            n -= 1;
            char c = n%26+A;
            res = c+res;
            n /= 26;
        }
        return res;
    }
};
View Code

Excel Sheet Column Number

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 

思路:

26进制转10进制,与2进制转10进制一样。

题解:

技术分享
class Solution {
public:
    int titleToNumber(string s) {
        int res = 0;
        for(int i=0;i<s.size();i++) {
            char c = s[i];
            int tmp = c-A+1;
            res = res*26+tmp;
        }
        return res;
    }
};
View Code

 

[leetcode] Excel Sheet Column Title & Excel Sheet Column Number

标签:

原文地址:http://www.cnblogs.com/jiasaidongqi/p/4202794.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!