您的位置:首页 > 其它

【LeetCode】Excel Sheet Column Title

2015-03-15 21:21 507 查看
Excel Sheet Column Title 问题描述见链接。

在这个问题中,其实设计的是类似于二进制、十六进制的一种进位方式,可以认为是二十六进制,然而难点在于A-Z中没有0这个数,也就是说Z=26这个值,如果用普通的短除法取余数,如果余数中遇到0,就需要向上一级借1来表达Z这个值。

方法一:

我设计了如下的算法实现。

1. 进行短除法,获取由余数组成的数列

2. 将得到的余数从正序第一位开始检查0(或小于0,假设为current),如果遇到就转换成(26+current),并向后一位借1,一位一位检查

3. 不检查最后一位,因为最高位一定大于等于1,而借位不会超过1,因此一定是一个大于等于0的数

4. 逆序输出数列,找到对应的字母。如果遇到0则跳过(其实只有最后一位可能为0,但由于是输出的最高位,因此需要跳过)

public class ExcelSheetColumnTitle {

public static final Character[] LETTER_ARRAY = { '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' };

public List<Integer> remainderArray = new ArrayList<Integer>();

public String convertToTitle1(int n) {
if (n == 0) {
return "";
}

String columnTitle = "";

int remainder = 0;
int quotient = 0;
while ((quotient = n / 26) > 0) {
remainder = n % 26;

remainderArray.add(remainder);

n = quotient;
}
remainder = n % 26;
remainderArray.add(remainder);

checkZ(0);

for (int i = remainderArray.size() - 1; i >= 0; i--) {
if (remainderArray.get(i) == 0) {
continue;
}

columnTitle += LETTER_ARRAY[remainderArray.get(i) - 1];
}

return columnTitle;
}

public void checkZ(int checkIndex) {
if (checkIndex >= (remainderArray.size() - 1)) {
return;
}

int current = remainderArray.get(checkIndex);
if (current <= 0) {
remainderArray.set(checkIndex, 26 + current);

int next = remainderArray.get(checkIndex + 1);
remainderArray.set(checkIndex + 1, next - 1);
}

checkZ(checkIndex + 1);
}

}
上述结果是正确的,但是太复杂了。参考了别人的方法后发现,这其实可以用很简单的方法解决。

方法二:

第二种方法简单许多。为了解决Z在短除法中需要借位来表示的问题,在算法设计中,直接每次循环都把N减1,然后得到的余数自然也会在原来的基础上减1,Z所对应的数字自然变成了25,与'A’的ASCII码相加,正好得到‘Z’的ASCII码。把转换出来的字符拼接在输出字符串前,最后进行整除。代码如下:

<span style="white-space:pre"> </span>public String convertToTitle(int n) {
String columnTitle = "";

while (n > 0) {
n--;
columnTitle = (char)((n % 26) + 'A') + columnTitle;

n = n /26;
}

return columnTitle;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode