leetcode 之Excel Sheet Column Title

Total Accepted: 9173 Total Submissions: 52899

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

这是第一次想出来的方案

只是马上就想出来 就写了。结果发现有很多不严谨的地方,然后又仔细考虑了一下这个题

	public static String convertToTitle(int n) {
		char[] Map = { ' ', '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 result = "";
		while (n >= 26) {
			result += 'Z';
			n -= 26;
		}
		if (n > 0) {
			result += Map[n];
		}

		return result;

	}

分析思路:

这道题和转进制有一点不同,因为他没有0,而且是27进制的没有0的一个计数法则。

比如26是Z。27就是AA。

所以尾数的是n%27为下标的Map值。

倒数第二位是有几个26为下标但是有一个就不算,比如27是有一个26加一个1,就是AA。

但是如果是52呢,就是有两个26,但正确答案应该是AZ,所以我的处理办法是先让n-1再除

最后成功Accepted

import java.util.Arrays;

public class Main {

	public static void main(String[] args) {

		System.out.println(convertToTitle(26));
		System.out.println(convertToTitle(27));
		System.out.println(convertToTitle(52));
		System.out.println(convertToTitle(701));
		System.out.println(convertToTitle(703));
	}

	public static String convertToTitle(int n) {
		char[] Map = { 'Z', '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' };
		int tail = n % 26;
		String result = "" + Map[tail];
		int num = (n - 1) / 26;
		while (num > 0) {
			result = Map[num % 26] + result;
			num =(num-1)/ 26;
		}

		return result;

	}
}










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值