【发布时间】:2017-04-16 00:43:54
【问题描述】:
我正在尝试尽可能高效地生成所有 2^n(并将它们保存到数组中),例如 0001 0010 0011 等等 其中 n 最大可达 15。
这是我的代码:
public static void main(String args[]) {
final long startTime = System.nanoTime();
final int N = 15;
int m = (int) Math.pow(2, N) - 1;
int[][] array = new int[m][N];
int arrLength = array.length;
for (int i = 0; i < arrLength; i++) {
String str = String.format("%" + N + "s", Integer.toBinaryString(i + 1)).replace(' ', '0');
for (int j = 0; j < N; j++) {
array[i][j] = Character.getNumericValue(str.charAt(j));
}
}
final long duration = System.nanoTime() - startTime;
double sec = (double) duration / 1000000000.0;
System.out.println(sec);
}
关于如何更快地做到这一点的任何建议? 截至目前,我的计时器说它需要 ~0.1 到 ~0.12
【问题讨论】:
-
1) 如果您想要
2^n组合,为什么要创建大小为2^n-1的数组? --- 2) 由于m已经是数组大小,arrLength = array.length相当多余。 --- 3)Math.pow(2, N)最好写成1 << N。 --- 4) 当您将long值与double值相除时,long值会自动将promoted 转换为double,因此无需强制转换。 -
@Andreas 感谢您的反馈,我忘了说我想跳过第一个组合(0000)!
标签: java optimization binary