【LeetCode】Excel Sheet Column Title

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;
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值