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.
Subscribe to see which companies asked this question
解法:和Excel Sheet Column Number相反,这次是10进制转26进制。从低位往高位求,每进一位,则把原数缩小26倍,再对26取余,之后减去余数,再缩小26倍,以此类推,可以求出各个位置上的字母。最后只需将整个字符串翻转一下即可。
class Solution { public: string convertToTitle(int n) { string res = ""; while (n > 0) { int rem = n % 26; if (rem == 0) { res += "Z"; n -= 26; } else { res += (char)(rem - 1 + ‘A‘); n -= rem; } n /= 26; } reverse(res.begin(), res.end()); return res; } };
时间: 2024-10-14 00:19:39