LeetCode - Excel Sheet Column

原创 2015年07月10日 00:21:05

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进制转换。

class Solution {
public:
    string convertToTitle(int n) {
        string ans;
        int b[10] = {1};
        int sum[10] = {0};
        sum[0] = 26;
        int m = n, i = 0;
        while(double(b[i]) < m / 26.0){
            b[i + 1] = b[i] * 26;
            ++i;
            m -= b[i];
            sum[i] = sum[i - 1] + b[i] * 26;
        }
        if(i > 0) n -= sum[i - 1];
        while(i > 0){
            int t = (n - 1) / b[i];
            n = n - t * b[i];
            ans += char(t + 65);
            i--;
        }
        ans += char(n + 64);
        return ans;
    }
};

更简单的:

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




相关文章推荐

Leetcode 171. Excel Sheet Column Number

Related to question Excel Sheet Column TitleGiven a column title as appear in an Excel sheet, return...

[LeetCode]--168. Excel Sheet Column Title

Given a positive integer, return its corresponding column title as appear in an Excel sheet.For exam...

[C++]LeetCode: 57 Excel Sheet Column Title

题目: Given a positive integer, return its corresponding column title as appear in an Excel sheet. F...

LeetCode 168. Excel Sheet Column Title 解题报告

题目描述: 168. Excel Sheet Column Title   Given a positive integer, return its corresponding ...

[LeetCode]168.Excel Sheet Column Title

【题目】 Given a positive integer, return its corresponding column title as appear in an Excel sheet. ...

[LeetCode][171][Excel Sheet Column Number]

题目链接:https://leetcode.com/problems/excel-sheet-column-number/ 题目描述: Given a column title a...

LeetCode笔记:171. Excel Sheet Column Number

模仿处理excel中的列

LeetCode Factorial Trailing Zeroes, Excel Sheet Column Number

Factorial Trailing Zeroes 题意:给一个数n,问n!的末尾有几个0 第一反应是0只有2、5相遇能出一个0,所以n有几个5的倍数似乎就是答案了。 (n!有k个5,肯定有k个2,能...

LeetCode之路:171. Excel Sheet Column Number

LeetCode之路:171. Excel Sheet Column Number 一、引言这道题相对来说比较简单,但是背后涉及到的东西确实挺有意思的: 我才知道 Excel 的列的表示是用的类似...

leetcode 之Excel Sheet Column Title

Total Accepted: 9173 Total Submissions: 52899 Given a positive integer, return its corres...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode - Excel Sheet Column
举报原因:
原因补充:

(最多只允许输入30个字)