一种字符串和数字的对应关系

//一种字符串和数字的对应关系
public class StrMatchInt{
	
    //K伪进制表示法
    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++]=getKthCharAtChs(chs,nCur+1);
    	  	 n%=cur;
    	  }while(index!=res.length);
    	  return String.valueOf(res);
    }

    //获得第k个位置的字符
    public static char getKthCharAtChs(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+=getNthFromChar(chs,strc[i])*cur;
    	 	  cur*=base;
    	 }
    	 return res;
    }
    public static int getNthFromChar(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)
	{
		 //System.out.println("Hello");
       char[] chs = { '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 len = 1;
		String res = "";
		for (int i = 1; i != 705; i++) {
			res = getString(chs, i);
			if (res.length() != len) {
				len = res.length();
				System.out.println("========================");
			}
			System.out.print(res + " ");
			if (i % chs.length == 0) {
				System.out.println();
			}
		}
		System.out.println();
		System.out.println("========================");
		int testNum = 78128712;
		System.out.println(getNum(chs, getString(chs, testNum)));
		String testStr = "BZZA";
		System.out.println(getString(chs, getNum(chs, testStr)));


	}
}
1000
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值