您的位置:首页 > 其它

[LeetCode] Excel Sheet Column Title 求Excel表列名称

2015-01-16 07:22 477 查看
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.

此题和Excel Sheet Column Number 求Excel表列序号是一起的,但是我在这题上花的时间远比上面一道多,起始原理都一样,就是一位一位的求,此题从低位往高位求,每进一位,则把原数缩小26倍,再对26取余,之后减去余数,再缩小26倍,以此类推,可以求出各个位置上的字母。最后只需将整个字符串翻转一下即可。 代码如下:

解法一:

class Solution {
public:
string convertToTitle(int n) {
string res = "";
while (n) {
if (n % 26 == 0) {
res += 'Z';
n -= 26;
}
else {
res += n%26 - 1 + 'A';
n -= n%26;
}
n /= 26;
}
reverse(res.begin(), res.end());
return res;
}
};


然后我们可以写的更简洁一些:

解法二:

// Non-recursion
class Solution {
public:
string convertToTitle(int n) {
string res;
while (n) {
res += --n % 26 + 'A';
n /= 26;
}
return string(res.rbegin(), res.rend());
}
};


这道题还可以用递归来解,而且可以丧心病狂的压缩到一行代码来解:

解法三:

class Solution {
public:
string convertToTitle(int n) {
return n == 0 ? "" : convertToTitle(n / 26) + (char)(--n % 26 + 'A');
}
};


类似题目:

Excel Sheet Column Number

参考资料:

https://leetcode.com/discuss/19024/simple-c-code

https://leetcode.com/discuss/19047/my-1-lines-code-in-java-c-and-python

LeetCode All in One 题目讲解汇总(持续更新中...)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: