首先这不是家庭作业!
我的问题来自 Robert Sedgewick 的《C++ 算法第三版》一书。
给定一个大小为 n × 2^n(二维)的数组,我们应该用大小正好为 n 的二进制数来填充它。例如,对于 n=5,结果将是:
00001
00010
00011
00100
00101
00110
00111
等等。我们应该将这个位序列放入数组中。
最佳答案
这是一个非常基本的问题,我将用这个 Java 代码片段进行演示:
public class Bin { // prints:
static String zero(int L) { // 0000
return (L <= 0 ? "" : String.format("%0" + L + "d", 0)); // 0001
} // 0010
static String zeroPad(String s, int L) { // 0011
return zero(L - s.length()) + s; // 0100
} // 0101
public static void main(String[] args) { // 0110
final int N = 4; // 0111
for (int i = 0; i < (1 << N); i++) { // 1000
System.out.println(zeroPad(Integer.toBinaryString(i), N)); // 1001
} // 1010
} // 1011
} // 1100
// 1101
// 1110
// 1111
我将让您弄清楚如何实现 toBinaryString
以及如何使用位填充 int[][]
。
关于algorithm - 用二进制数填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2795678/