以上是问题。
我能够找到一种递归方法,但想出迭代方法很麻烦。 ChatGPT 给了我一个片段。
import java.util.*;
public class IterativeCombinationWithoutBitManipulation {
public static void main(String[] args) {
int n = 2; // Number of boolean variables
int totalCombinations = (int) Math.pow(2, n);
for (int i = 0; i < totalCombinations; i++) {
int temp = i;
boolean[] values = new boolean[n];
for (int j = 0; j < n; j++) {
values[j] = temp % 2 == 1;
temp /= 2;
}
for (boolean value : values) {
System.out.print(value + " ");
}
System.out.println();
}
}
}
这里我想知道第二个for循环中发生了什么?当进一步询问提示时,模数和除法被告知正在进行某种数字的二进制转换并转换为布尔值。我还想知道为什么选择 'i' 的值作为 'temp' 变量的值。
这将帮助我在解决不同类型的问题时将逻辑迁移到这些问题上。谢谢!
打印他们可以假设的所有可能的真值组合
这就是二进制的工作原理。所以它本质上是在问:“打印 0-N 中的每个二进制数,其中 0 为 False,1 为 True
好吧,我们一行一行地来吧
int totalCombinations = (int) Math.pow(2, n);
根据定义,这是正确的。用 n 位二进制表示的最大数字是 2^n-1。当您添加零作为选项时,不同数字的数量将变为 2^n。想一想,用 2 位数字:
00,01,10,11 -> 0,1,2,3 -> 4 个选项
for (int i = 0; i < totalCombinations; i++) {
我们知道我们将不得不打印
totalCombination
次。
int temp = i;
boolean[] values = new boolean[n];
创建 i 的副本,因为我们稍后要更改它并创建一个位置来存储布尔数组(二进制数)
for (int j = 0; j < n; j++) {
values[j] = temp % 2 == 1;
temp /= 2;
}
这比我们迄今为止处理的情况要复杂一些。这个 for 循环本质上将
temp
转换为二进制数,并将每个 1 和 0 作为 true 和 false 存储在 values
中
for (boolean value : values) {
System.out.print(value + " ");
}
打印每个布尔值
System.out.println();
新线路。