java 10进制和5进制互转 生成的唯一邀请码

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.util.Date;
import java.util.Objects;
import java.util.Random;

import static java.time.ZoneId.SHORT_IDS;

/**

 */
public class Main {

    private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);

    // 对应5进制的值: a->0,1->1,b->2,2->3,c-4
    private static  final char [] ARRAY = {'a','1','b','2','c'};
    private static final String OTHER_CHAR = "A";
    private static final int DECIMAL = 5;

    /**
     * 根据id获取对应字符串
     * 10 进制转化 decimal
     * @param id
     */
    private static String passedBy(long id,Integer decimal){
        char [] resultArray = new char[DECIMAL];
        int length = ARRAY.length;
        while ((id/decimal) > 0){
            int mod = (int)id%decimal;
            resultArray[--length]= ARRAY[mod];
            id = id /decimal;
        }
        if(length > 0){
//            防止达到array所代表进制的最大值报错,当达到进制所表示的最大值时此时是aaaaa
            resultArray[--length] = ARRAY[(int)id%decimal];
        }
        String resultStr = new String(resultArray,length,(ARRAY.length-length));
        if(resultStr.length() < decimal){
            StringBuilder sb = new StringBuilder();
            sb.append(OTHER_CHAR);
            Random random = new Random();
            for(int i = resultStr.length()+1;i < ARRAY.length;i++){
                sb.append(ARRAY[random.nextInt(ARRAY.length)]);
            }
            resultStr += sb.toString();
        }
        return resultStr;
    }

    private static int passedByChar(String para){
        int  index = para.indexOf(OTHER_CHAR);
        if(index < 0){
            return getIdByPara(para);
        }else {
            return getIdByPara(para.substring(0,index));
        }
    }

    private static int getIdByPara(String subStr){
//      进制表示的最大转化数据 当
        if(Objects.equals("aaaaa",subStr)){
            return (int)Math.pow(DECIMAL,subStr.length());
        }
        int sum = 0;
        char [] subCharArray  = subStr.toCharArray();
        int length = subCharArray.length;
//      例子:   sum +=
        /**例子: bb2aA
         * sum += 2*(5^3)+2*(5^2)+3*(5^1)+0*(5^0)
         */
        for(int i = 0;i < length;i++){
            for(int j = 0;j < DECIMAL;j++){
                if(Objects.equals(subCharArray[i],ARRAY[j])){
                    sum = sum + j * (int)Math.pow(DECIMAL,(length-i-1));
                    break;
                }
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        int test = 315;
        System.out.println(test);
        String result = passedBy(test,5);
        System.out.println(result);
        System.out.println(passedByChar(result));
    }

}

你可能感兴趣的:(java)