题意:A字符串为12345,第一次拓展后A变成12345$54321,以后的第i次变成上一次的A+i个$+A的倒置,这样无限延伸,给出一个long类型的pos,求该位置的字符。
题解:long类型处理是难点,为了避开我们只好采用对折,首先要明白变换中的基础单元是12345$54321,而对于给定的pos,它必定是关于n个$对称的,所以我们就要去求出基础单元折多少次时,字符串的总长度才能包括pos,得到次数后其实n也就得到了,这时我们把pos折回左半边,转化成了求一个更小的pos,这样一直转化到11以内。特别需要注意的是要记得判定当前的pos在不在$符号上,只需要判断上一次的pos是否不大于上一次的length+这次的$数n即可。
import java.util.*;
public class Main {
public static long find(long pos){
int charnum = 2;
long length = 11;
while(length*2+charnum<pos){
length = length*2+charnum;
charnum++;
}
if(pos<=length+charnum){
return 0;
}else{
pos = length-(pos-length-charnum)+1;
return pos;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int e_num = scan.nextInt();//测试数
while(e_num>0){
long pos = scan.nextLong();
while(pos>11 && pos!=0){
pos = find(pos);
}
if(pos==0){
System.out.println("$");
}else{
int p = (int) pos;
String str = "12345$54321";
System.out.println(str.charAt(p-1));
}
e_num --;
}
}
}