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; } };
时间: 2024-10-07 18:18:23