L1-2 倒數第N個字符串 (15分) java

給定一個完全由小寫英文字母組成的字符串等差遞增序列,該序列中的每個字符串的長度固定爲 L,從 L 個 a 開始,以 1 爲步長遞增。例如當 L 爲 3 時,序列爲 { aaa, aab, aac, ..., aaz, aba, abb, ..., abz, ..., zzz }。這個序列的倒數第27個字符串就是 zyz。對於任意給定的 L,本題要求你給出對應序列倒數第 N 個字符串。

輸入格式:

輸入在一行中給出兩個正整數 L(2 ≤\le L ≤\le 6)和 N(≤105\le 10^5105)。

輸出格式:

在一行中輸出對應序列倒數第 N 個字符串。題目保證這個字符串是存在的。

輸入樣例:

3 7417

輸出樣例:

pat
import java.io.IOException;
import java.io.*;
import java.util.*;

//** Class for buffered reading int and double values *//*
class Reader {
	static BufferedReader reader;
	static StringTokenizer tokenizer;

	// ** call this method to initialize reader for InputStream *//*
	static void init(InputStream input) {
		reader = new BufferedReader(new InputStreamReader(input));
		tokenizer = new StringTokenizer("");
	}

	// ** get next word *//*
	static String next() throws IOException {
		while (!tokenizer.hasMoreTokens()) {
			// TODO add check for eof if necessary
			tokenizer = new StringTokenizer(reader.readLine());
		}
		return tokenizer.nextToken();
	}

	static String nextLine() throws IOException {
		return reader.readLine();
	}

	static int nextInt() throws IOException {
		return Integer.parseInt(next());
	}

	static long nextLong() throws IOException {
		return Long.parseLong(next());
	}

	static double nextDouble() throws IOException {
		return Double.parseDouble(next());
	}
}

public class Main {
	
	public static void main(String[] args) throws IOException {
		Reader.init(System.in);
		int l = Reader.nextInt();
		int n = Reader.nextInt();
		char[]ans = new char[l];

		int total = (int)(Math.pow(26, l));//總計結果數
		n = total-n;//正着數第幾個
		int index=0;
		while (n>0) {
			int t = n%26;
			ans[index++] = (char)(t+'a');
			n /=26;
		}
		for (int i = 0; i < l-index; i++) {
			System.out.print('a');
		}
		for (int i = index-1; i >=0 ; i--) {
			System.out.print(ans[i]);
		}
			
	}
}

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