[leetcode] 168.Excel Sheet Column Title

来源:互联网 发布:剑亭网络武侠小说 编辑:程序博客网 时间:2024/05/16 11:53

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

For example:

1 -> A2 -> B3 -> C...26 -> Z27 -> AA28 -> AB

题意:
给定一个正数,返回它在excel中对应的列号。如上面所示,这是一个26进制的转换。
思路:
采用递归的方法,当前数字的模26就是该位置对应的数字,而当前数字除26是该位置之前对应的结果,把之前的结果拼接上这个位置的结果就是最终结果。因为需要先计算前面的结果,所以采用递归的方法。
代码如下:

class Solution {public:    string convertToTitle(int n) {        if(n == 0)return "";        string result = "";        if(n > 26)        {            result = convertToTitle( (n - 1)/26);        }        result.push_back('A' + (n - 1) % 26);        return result;    }};
0 0
原创粉丝点击