首页 > 其他 > 详细

[LeetCode] Excel Sheet Column Title

时间:2015-07-14 19:34:16      阅读:92      评论:0      收藏:0      [点我收藏+]

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 

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases.

 

Hide Tags
 Math
Hide Similar Problems
 (E) Excel Sheet Column Number
 
分析:本质上是10进制到26进制的转换,但是 由于下标从1开始而不是从0开始,因此要减一操作。
 
1 --》A
26--》Z
 
先取出余数,然后将其转换成字符A~Z,
然后n= (n-1)/26,将26进制的数右移一位,然后从新做判断。。
 
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;

void printArray(int *array, int size)
{
    for(int i = 0; i < size; i++)
        cout << array[i]<< "\t" ;
    cout << endl;
}


void printVector(vector<int> array )
{
    for(int i = 0; i <array.size(); i++)
        cout << array[i]<< "\t" ;
    cout << endl;
}

class Solution {
    public:
        string convertToTitle(int n) {
            string str;
            int a = 0;
            while(n)
            {   
                a = (n-1) % 26; 
                str += char(a + A‘);
                n = (n-1)/26;
            }   
            reverse(str.begin(), str.end());
            return str;
        }
};

#if 0
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB 
#endif


int main()
{
    Solution sl;
    cout << sl.convertToTitle(1) <<endl;
    cout << sl.convertToTitle(100) <<endl;
    cout << sl.convertToTitle(1000) <<endl;

    cout << endl;
    return 0;
}

 

 
 

[LeetCode] Excel Sheet Column Title

原文:http://www.cnblogs.com/diegodu/p/4645920.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!