LeetCode No.168
给定一个正整数,返回它在 Excel 表中相对应的列名称。
例如,
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
...
示例 1:
输入: 1
输出: "A"
示例 2:
输入: 28
输出: "AB"
示例 3:
输入: 701
输出: "ZY"
解题思路:构建map容器用于存储显示的字符。本题通过 number 除以26得到的 remainder,即得到最后一位的字符。然后将 quotient 赋值给 number,依次循环。
需要注意的是边界字符,即如 26、52之类。所以需要加一个判断条件,即当 quotient 大于0且 remainder 为0时,需要 quotient - 1,并且添加字符 Z
//168 string convertToTitle(int n) { if(n<1) return ""; map<short,char> m{ {1,'A'},{2,'B'},{3,'C'},{4,'D'},{5,'E'},{6,'F'},{7,'G'},{8,'H'},{9,'I'},{10,'J'}, {11,'K'},{12,'L'},{13,'M'},{14,'N'},{15,'O'},{16,'P'},{17,'Q'},{18,'R'},{19,'S'},{20,'T'}, {21,'U'},{22,'V'},{23,'W'},{24,'X'},{25,'Y'},{26,'Z'} }; string res; int quotient = n, reminder; while(quotient>0) { reminder=quotient%26; quotient=quotient/26; if(quotient>0 && reminder==0) { quotient -=1; res ='Z' + res; } else res = m[reminder] + res; } return res; }//168