Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1, A 2, B 3, C ... AB, AA, Z
Problem Solving Ideas:
The boundary condition of z= 26 needs to be considered. My code is discussed in detail, the reference code is very clever, with n--
The key is n--
. The minimum in 26-bit number are mapped to 1, not 0.
Java Code:
1.
PublicString Converttotitle (intN) {if(N < 1) { return""; } StringBuilder S=NewStringBuilder (); CharA = ' a '; while(N >= 1) { intx = n%26; if(x = = 0) {a= ' Z '; N= N/26-1; }Else{a= (Char) (' A ' + x-1); N= N/26; } s.append (a); } returns.reverse (). toString (); }
2. Reference code, better.
PublicString Converttotitle (intN) {if(n <= 0){ Throw NewIllegalArgumentException ("Input is not valid!"); } StringBuilder SB=NewStringBuilder (); while(N > 0) {n--; CharCH = (Char) (n% + ' A '); N/= 26; Sb.append (CH); } returnsb.reverse (). toString (); }
Reference:
1. http://www.programcreek.com/2014/03/leetcode-excel-sheet-column-title-java/
Leetcode Excel Sheet Column Title