03-指定位数随机数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.Random;

public class NumUtil {
/**
* 生成指定位数的随机数 - 10的次幂运算控制位数
*
* @param len 随机数长度
* @return 指定位数的随机数
*/
public static int createNum(int len) {
Random random = new Random();
// len = 4
// max = 10^4 即 10000 - 10^3 即 1000 = 9000
int max = (int) (Math.pow(10, len) - Math.pow(10, len - 1));
// random.nextInt() 前开后闭
// 0~8999 + 1000 = 1000~9999
return random.nextInt(max) + (int) Math.pow(10, len - 1);
}

// test
public static void main(String[] args) {
for (int i = 1; i < 50; i++) {
int num = createNum(4);
System.out.println("num1 = " + num);
}
}
}

03-指定位数随机数
https://janycode.github.io/2017/06/28/20_收藏整理/02_算法题/03-指定位数随机数/
作者
Jerry(姜源)
发布于
2017年6月28日
许可协议