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
解题思路:
需要考虑Z= 26 的边界情况。我的代码分情况讨论,参考代码很巧妙,用n--
The key is n--
. The minimum in 26-bit number is mapped to 1, not 0.
Java code:
1.
public String convertToTitle(int n) { if(n < 1) { return ""; } StringBuilder s = new StringBuilder(); char a = 'A'; while(n >= 1) { int x = n%26; if( x == 0) { a = 'Z'; n = n/26 - 1; }else { a = (char)('A' + x - 1); n = n/26; } s.append(a); } return s.reverse().toString(); }
2. 参考代码,更好。
public String convertToTitle(int n) { if(n <= 0){ throw new IllegalArgumentException("Input is not valid!"); } StringBuilder sb = new StringBuilder(); while(n > 0){ n--; char ch = (char) (n % 26 + 'A'); n /= 26; sb.append(ch); } return sb.reverse().toString(); }
Reference:
1. http://www.programcreek.com/2014/03/leetcode-excel-sheet-column-title-java/