168. Excel Sheet Column Title
题目:
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
链接: http://leetcode.com/problems/excel-sheet-column-title/
题解:
转换数字和excel column title。数学题,写几个例子找到规律就可以了,比如53, 52, 26, 27等等。规律是,当n > 0时, 假如n % 26 == 0,则n为26的倍数,要转换为'Z'插入队首,之后n = n / 26 - 1, 假如n % 26 != 0, 则使用一般方法计算字符,int c = 'A' + n % 26 - 1, 之后 n /= 26。
Time Complexity - O(N), Space Complexity - O(1)。
public class Solution { public String convertToTitle(int n) { if(n <= 0) return ""; StringBuilder result = new StringBuilder(); while(n > 0) { if(n % 26 == 0) { // n is multiple of 26, example - 52 - 'AZ' result.insert(0, 'Z'); n = n / 26 - 1; } else { int c = 'A' + n % 26 - 1; // example - 27 - 'AA' result.insert(0, (char)c); n /= 26; } } return result.toString(); } }
二刷:
二刷好好参考了解答。 使用了一个很巧妙的小技术,把n映射到0-25这26个数字里,我们可以先n--, 然后再进行后面的转换 - n % 26 + 'A', 最后n /= 26.
这个小技巧和Permutation Sequence很像,要好好学习。
Java:
public class Solution { public String convertToTitle(int n) { if (n < 1) { return ""; } StringBuilder sb = new StringBuilder(); while (n > 0) { n--; sb.insert(0, (char)(n % 26 + 'A')); n /= 26; } return sb.toString(); } }
三刷:
二刷理解得不深刻。
public class Solution { public String convertToTitle(int n) { if (n <= 0) return ""; StringBuilder sb = new StringBuilder(); while (n > 0) { n--; sb.insert(0, (char)('A' + n % 26)); n /= 26; } return sb.toString(); } }
一刷的方法,用例子出发 - 'AZ' = 52, - 'AA' = 27
public class Solution { public String convertToTitle(int n) { if (n <= 0) return ""; StringBuilder sb = new StringBuilder(); while (n > 0) { if (n % 26 == 0) { sb.insert(0, 'Z'); // 52 = "AZ" n = n / 26 - 1; } else { sb.insert(0, (char)(n % 26 - 1 + 'A')); // 27 = "AA" n = n / 26; } } return sb.toString(); } }
Reference:
https://leetcode.com/discuss/19047/my-1-lines-code-in-java-c-and-python
https://leetcode.com/discuss/19044/share-simple-solution-just-little-trick-handle-corner-case
https://leetcode.com/discuss/34526/share-my-java-solusion
https://leetcode.com/discuss/25667/short-solution-without-using-string-buffer-string-builder
https://leetcode.com/discuss/19135/solution-with-explanation
https://leetcode.com/discuss/82531/my-easy-to-understand-java-solution