PTA 倒数第N个字符串 Java
题目相当于是做进制转换,‘z’表示0,‘a’表示25
则将十进制数N转换成26进制(‘z’~‘a’),不足L位用’z’(0)填充
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
Reader.init(System.in);
Writer.init(System.out);
slove();
Writer.close();
}
// 解答入口
static void slove() throws IOException {
int l = Reader.nextInt();
// 转化成26进制进行计算,'a' = 25 ,'z' = 0
// 字符使用ASCII 进行换算
// 'a' = 25- 25 + 'a' 'z' = 25 - 0 + 'z'
// 因为倒数第一个是'zzz'就是'000'
// 即求倒数第1个数字是值为'0‘的时候
int n = Reader.nextInt() - 1;
// 这里使用StringBuilder 为了后面倒序输出
StringBuilder s = new StringBuilder();
while (n > 0) {
int tmp = n % 26;
s.append((char) (25 - tmp + 'a'));
n /= 26;
}
// 补上前导0,即'z'
int add = l - s.length();
for (int i = 0; i < add; i++) {
s.append('z');
}
// 倒过来输出
Writer.print(s.reverse());
}
}
class School {
ArrayList<String> ids;
int capacity;
School(int capacity) {
this.capacity = capacity;
ids = new ArrayList<String>(capacity);
}
}
// 以下是输入输出模板和思路逻辑无关
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()) {
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 char nextChar() throws IOException {
return next().toCharArray()[0];
}
static float nextFloat() throws IOException {
return Float.parseFloat(next());
}
static Double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
class Writer {
static BufferedWriter writer;
static void init(OutputStream outputStream) {
writer = new BufferedWriter(new OutputStreamWriter(outputStream));
}
static void print(Object object) throws IOException {
writer.write(object.toString());
}
static void println(Object object) throws IOException {
writer.write(object.toString());
writer.write("\n");
}
static void close() throws IOException {
// TODO Auto-generated method stub
writer.close();
}
}