[LeetCode] 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 

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]<< "	" ;
    cout << endl;
}


void printVector(vector<int> array )
{
    for(int i = 0; i <array.size(); i++)
        cout << array[i]<< "	" ;
    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;
}
 
 
原文地址:https://www.cnblogs.com/diegodu/p/4645920.html