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;

	}
}










發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章