java生成有顺序的邀请码

将int类型有顺序的字符串组合相互转换
import java.util.HashMap;
import java.util.Map;

public class CodeTest {


    private static final char[] allChar = new char[]{'D', 'H', 'K', 'A', '4', 'S', 'G', '8', 'B', 'J', 'C', 'L', 'X', '2', 'P', 'E', '6', '5', '7', '9', 'M', '3', 'Y', 'R', 'F', 'T', 'U', 'V', 'W', 'N', 'Q', 'Z'};

    private static final Map<String, Integer> charAndNum = new HashMap<>();

    private static final int codeSize = 6;


    public static String getCodeByUid(int num) {
        char[] buf = new char[32];
        int charPos = 32;
        while ((num / allChar.length) > 0) {
            buf[--charPos] = allChar[(num % allChar.length)];
            num /= allChar.length;
        }
        buf[--charPos] = allChar[(num % allChar.length)];
        String str = new String(buf, charPos, (32 - charPos));
        if (str.length() < codeSize) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < codeSize - str.length(); i++) {
                sb.append(allChar[0]);
            }
            sb.append(str);
            str = sb.toString();
        }
        return str;
    }


    public static int getUidByCode(String code) {
        if (code == null) {
            return 0;
        }
        char[] codet = code.toCharArray();
        for (char a : codet) {
            if (!(a >= '1' && a < '9' || a >= 'A' && a <= 'Z' || a >= 'a' && a <= 'z')) {
                return 0;
            }
        }
        code = code.toUpperCase();
        char[] codes = code.toCharArray();
        if (codes.length != codeSize) {
            return 0;
        }
        int uid = 0;
        for (int i = 0; i < codes.length; i++) {
            uid += charAndNum.get(String.valueOf(codes[i])) * Math.pow(allChar.length, codes.length - i - 1);
        }
        return uid;
    }

    public static void main(String[] args) {
        if (charAndNum.size() == 0) {
            for (int i = 0; i < allChar.length; i++) {
                charAndNum.put(String.valueOf(allChar[i]), i);
            }
        }
        int uid = getUidByCode("DJ5F5Z");
        System.out.println(uid);
        System.out.println(getCodeByUid(10019391));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值