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
想法就是转换成我们熟悉的从0开始的每次对每一位处理都要先减去1/*what if we assume that A equals to 0*/ public class Solution { public String convertToTitle(int n) { StringBuffer result=new StringBuffer(); while(n>0){ n--; char a=(char)(n%26+'A'); result.append(a); n=n/26; } return result.reverse().toString(); } }
方法2
public class Solution { public String convertToTitle(int n) { StringBuffer result=new StringBuffer(); while(n>0){ int remain=n%26; if(remain==0){ result.append("Z"); n=n/26-1; }else{ char a=(char)(remain-1+'A'); result.append(a); n=n/26; } } return result.reverse().toString(); } }