168.Excel Sheet Column Title Excel表列名称


本人解法 ~略麻烦

class Solution {
    	public String convertToTitle(int n) {
		int flag = 0;
		String str = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z ";
		String[] arr = str.split(" ");
		String str2 = "";
		while(n!=0) {
			n--;//这个是最亮的一点  
			int temp=n%26;
			str2=arr[temp]+str2;
			n=n/26;
		}
		return str2;
	}
}

其他的解法 有点简单~~~~ 不用采用A~Z保存在一个数组中

public class Solution {
public String convertToTitle(int n) {
    String res = "";
    while(n != 0) {
        char ch = (char)((n - 1) % 26 + 65);
        n = (n - 1) / 26;
        res = ch + res;
    }
    return res;
}
}
class Solution {
    public String convertToTitle(int n) {
        StringBuilder sb = new StringBuilder();//用一个可变的字符串 节省一点时间
        while(n>0){
            if(n%26==0){
                sb.append('Z');
                n -= 26;
            }else {
                sb.append((char) ('A' + (n % 26) - 1));
            }
            n /= 26;
        }
        return sb.reverse().toString();
    }
}

最牛逼的一行解决

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

原文地址:https://www.cnblogs.com/cznczai/p/11149698.html