Generate a specified length verification code in Java
1. Method 1: high execution efficiency
/**
* 生成指定位数验证码,纯数字运算效率最高
*
* @param maxSize
* @return
*/
public static Long generateRandomCode(int maxSize) {
if (maxSize < 0) {
throw new BizException(ErrorCodeEnum.PARAM_ERROR);
}
//小数点后16位的double乘以10的指定次幂然后取整
String code = String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10, maxSize - 1)));
Long resultCode = Long.valueOf(code);
return resultCode;
}
2. Method 2: String interception
/**
* 生成指定位数验证码,字符串截取,效率不如方法一
*
* @param maxSize
* @return
*/
public static Long generateSubStringCode(int maxSize) {
if (maxSize < 0) {
throw new BizException(ErrorCodeEnum.PARAM_ERROR);
}
//16位double小数,取小数点后的2-8位
int startNum = 2;
int endNum = startNum + maxSize;
String code = (Math.random() + "").substring(startNum, endNum);
Long resultCode = Long.valueOf(code);
return resultCode;
}