168 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 

题目的意思大概是这样的意思大概是这样的,给定一个正数,返回在EXCEL表中的列标题
其实从栗子中可以看出来其实就是一个十进制转26进制的问题
下面给出我的解决方案:
方案一:
采用循环的方法,每次得到余数转成对应的字符的形式,添加到字符串中最后将这个字符串逆置
 1 class Solution {
 2 public:
 3    string convertToTitle(int n) {
 4           if(n<1) return "";
 5           else{
 6           string result="";
 7           char ch;
 8           while(n){
 9             n--;
10             ch = n%26+'A';
11             result+=ch;
12             n/=26;
13           }
14           reverse(result.begin(), result.end());
15           return result;
16           }
17     }
18 };

值得注意的是其中n--;这个是在n是26的倍数的时候出现的问题,如果是ch=n%26+64会出现'@'的情况

第二种方案:

    采用递归的方式

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 class Solution {
 5 public:
 6     string convertToTitle(int n) {
 7           static string s="";
 8           int p=0;
 9           if(n){
10              n--;
11              p = n%26;
12              convertToTitle(n/26);
13              if(p)
14                 s+=(char)(p+'A');
15           }
16           return s;
17     }
18 };
19 int main(){
20    Solution *s = new Solution;
21    //cout<<s->convertToTitle(28)<<endl;
22    cout<<s->convertToTitle(26);
23     return 0;
24 }

由于使用了static关键字,函数在连续调用的时候会出现问题所以没有通过AC,只是提供了一种思路。

第一种方案是可以AC的~

原文地址:https://www.cnblogs.com/xiaoysec/p/4423655.html