leetcode 168 Excel Sheet Column Title

来源:互联网 发布:菜谱软件ipad 编辑:程序博客网 时间:2024/06/05 06:34

Problem:
给一个数字,输出对应的字母编号,1-A, 26-Z,27-AA。
Solution:
考察的是进制的转换,难点在于对于26的倍数的处理,通过取余时-1然后再+1来实现。

Solution1:class Solution {public:    string convertToTitle(int n) {        return (n==0) ? "" : convertToTitle((n-1)/26) + char('A'+(n-1)%26);    }};Solution2:class Solution {public:    string convertToTitle(int n) {        string ans;        while(n) {            ans = char((n-1)%26 +'A') + ans;            n = (n-1)/26;        }        return ans;    }};
1 0
原创粉丝点击