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

[LeetCode] Excel Sheet Column Title

时间:2017-07-16 13:31:51      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:tle   lock   循环   public   计算   title   get   positive   --   

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 

给定一个整数,求出其在Excel对应的字母标题,利用while循环,先对整数取余(n - 1) % 26,找到数字与字母的关系,计算出最后一位的字母,然后对整数取商,计算下一位。最后将得到的结果字符串反转即可。

class Solution {
public:
    string convertToTitle(int n) {
        string s;
        int tmp = 0;
        while (n) {
            n = n - 1;
            tmp = n % 26;
            s += (A + tmp);
            n /= 26;
        }
        int left = 0, right = s.size() - 1;
        while (left <= right)
            swap(s[left++], s[right--]);
        return s;
    }
};
// 0 ms

相关题目:Excel Sheet Column Number

 

[LeetCode] Excel Sheet Column Title

标签:tle   lock   循环   public   计算   title   get   positive   --   

原文地址:http://www.cnblogs.com/immjc/p/7190181.html

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