题解 | #一种字符串和数字的对应关系#
一种字符串和数字的对应关系
http://www.nowcoder.com/practice/5020815008c649d7af1fef40c952c5eb
import java.util.Scanner; public class Main { public static String getString(char[]chs,int n){ if(chs==null||chs.length==0||n<1){ return ""; } int cur=1; int base= chs.length; int len=0; while (n>=cur){ len++; n-=cur; cur*=base; } char[] res=new char[len]; int index=0; int nCur=0; do{ cur/=base; nCur=n/cur; res[index++]=getK(chs,nCur+1); n%=cur; }while (index!=res.length); return String.valueOf(res); } //得到字符串数组的第k-1个字符 public static char getK(char[]chs,int k){ if(k<1||k> chs.length){ return 0; } return chs[k-1]; } /*字符串数组得到数字 * */ public static int getNum(char[]chs,String str){ if(chs==null||chs.length==0){ return 0; } char[] strc=str.toCharArray(); int base= chs.length; //进制 int cur=1; int res=0; for (int i = strc.length-1; i !=-1 ; i--) { res+=getNth(chs,strc[i])*cur; cur*=base; } return res; } //由字符得到对应数字 public static int getNth(char[] chs,char ch){ int res=-1; for (int i = 0; i < chs.length; i++) { if(chs[i]==ch){ res=i+1; break; } } return res; } public static void main(String[] args) { Scanner in = new Scanner(System.in); String[] stt1=in.nextLine().split(" "); int opt = Integer.parseInt(stt1[0]); int len = Integer.parseInt(stt1[1]); String str=in.nextLine(); char[] chs=str.toCharArray(); if(opt==1){ int n=in.nextInt(); System.out.println(getString(chs,n)); }else { String str_in=in.nextLine(); System.out.println(getNum(chs,str_in)); } } }