我需要能够创建一个组合的布尔数组,并通过程序运行它以查看它是否有效。如果没有,我将其丢弃并转到下一个组合。我的问题是我不知道如何创建此数组,因为n可以等于1-1000。所以我打算使用Integer.toBinaryString,但是由于它超过32岁时太大,因此无法使用。任何帮助都将非常有用。
谢谢!
“已接受的答案”指出:
经过测试,这将适用于较高的n值,例如10000等。
但这是不正确的。
public static void main(String[] args) {
final int n = 3;
for (int i = 0; i < Math.pow(2, n); i++) {
String bin = Integer.toBinaryString(i);
while (bin.length() < n)
bin = "0" + bin;
char[] chars = bin.toCharArray();
boolean[] boolArray = new boolean[n];
for (int j = 0; j < chars.length; j++) {
boolArray[j] = chars[j] == '0' ? true : false;
}
System.out.println(Arrays.toString(boolArray));
}
}
当n > 31
它将永远循环时,将重复前2 ^ 31个组合,因为i
它将溢出并且永远不会到达Math.pow(2, n)
。您可以轻松地用
public static void main2(String[] args){
int n = 32;
for (int i = 0; i < Math.pow(2, n); i++){
if (i == Integer.MIN_VALUE) {
// i overflows
System.out.println("i exceeded Integer.MAX_VALUE");
}
}
}
上面的代码将无限期地打印,i exceeded Integer.MAX_VALUE
但是可以使用BigInteger
循环的类似数据结构或类似的数据结构轻松地纠正此问题。以下代码适用于n <= Integer.MAX_VALUE
public static void main(String[] args) {
final int n = 32;
BigInteger bi = BigInteger.ZERO;
BigDecimal rows = new BigDecimal(Math.pow(2, n));
while (bi.compareTo(rows.toBigInteger()) < 0) {
String bin = bi.toString(2);//Integer.toBinaryString(i);
while (bin.length() < n)
bin = "0" + bin;
char[] chars = bin.toCharArray();
boolean[] boolArray = new boolean[n];
for (int j = 0; j < chars.length; j++) {
boolArray[j] = chars[j] == '0' ? true : false;
}
System.out.println(Arrays.toString(boolArray));
bi = bi.add(BigInteger.ONE);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句