【leetcode】168(Easy). Excel Sheet Column Title

解题思路:

相当于十进制转换为26进制,就是要控制一下余数不能是0


提交代码:
class Solution {
    public String convertToTitle(int n) {
        String res="";
        if(n<=0)	return res;
        
        int q,r;   //quotient residue
        String tmp="";
        while(n!=0) {
        	q=n/26;
        	r=n-q*26;
        	if(r==0) {
        		q--;r=26;
        	}
        	tmp+=(char)((int)'A'+r-1);
        	tmp+=res;
        	res=tmp;
        	tmp="";
        	n=q;
        }
        return res;
}
}

运行结果:
【leetcode】168(Easy). Excel Sheet Column Title


改了一下,使用StringBuilder:

class Solution {
    public String convertToTitle(int n) {
        String res="";
        if(n<=0)	return res;
        
        int q,r;   //quotient residue
        StringBuilder tmp=new StringBuilder();
        while(n!=0) {
        	q=n/26;
        	r=n-q*26;
        	if(r==0) {
        		q--;r=26;
        	}
        	tmp.append((char)((int)'A'+r-1));
        	tmp.append(res);
        	res=tmp.toString();
        	tmp.delete(0, tmp.length());
        	n=q;
        }
        return res;
}
}

运行结果:
【leetcode】168(Easy). Excel Sheet Column Title


讨论区有个大神的一行写法:

class Solution {
  return n == 0 ? "" : convertToTitle(--n / 26) + (char)('A' + (n % 26));
}

运行结果:
【leetcode】168(Easy). Excel Sheet Column Title
这里的convertToTitle功能是强制递归。