ITPub博客

首页 > > > [LeetCode] Excel Sheet Column Title

[LeetCode] Excel Sheet Column Title

作者:Ruiyuan Li 时间:2015-04-11 00:00:00 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

解题思路:

十进制转化成26进制。注意对于string类型来说,并不存在string=char+string类型操作符,只有string=string+char操作符。因此,可以用栈来存储低位,然后出栈。

另外一个需要注意的是(n-1)%26+'A',要n-1哈。

class Solution {
public:
    string convertToTitle(int n) {
        string result="";
        stack s;
        while(n!=0){
            s.push((n-1) % 26 + 'A');
            n = (n-1) / 26;
        }
        while(!s.empty()){
            result += s.top();
            s.pop();
        }
        return result;
    }
};

二次刷题(2015-08-05)

原来string类型的构造函数还可以这样string(int n, char c),表示n个c初始化string。

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


<!-- -->

原文作者:;如有侵权,请联系管理员删除。

上一篇: Azure搭建Openvpn
下一篇: [LeetCode] Sort List
请登录后发表评论 登录
全部评论

注册时间:2020-05-21

  • 博文量
    495
  • 访问量
    4825