【发布时间】:2013-07-28 20:08:07
【问题描述】:
我试图按 0 的升序打印二进制数(00 然后 01、10、11)。
使得零在前面。
我尝试使用来自 here 的以下代码,但这并没有给出正确的操作 (running sample)
void test2() {
final int grayCodeLength = 4;
// generate matrix
final int grayCodeCount = 1 << grayCodeLength; // = 2 ^ grayCodeLength
int grayCodeMatrix[][] = new int[grayCodeCount][grayCodeLength];
for (int i = 0; i < grayCodeCount; i++) {
int grayCode = (i >> 1) ^ i;
for (int j =0; j <grayCodeLength; j++) {
// extract bit
final int grayCodeBitMask = 1 << j;
grayCodeMatrix[i][j] = (grayCode & grayCodeBitMask) >> j;
}
}
// view result
for (int y = 0; y < grayCodeMatrix.length; y++) {
for (int x = 0; x < grayCodeMatrix[0].length; x++) {
System.out.print(grayCodeMatrix[y][x]);
}
System.out.print("\n");
}
}
但此操作不适用于 0 的升序。
所以我不得不处理这段代码中的字符串 (running sample)
class Main
{
static int k = 4;
public static void main (String[] args) throws java.lang.Exception
{
new Main().test7(k, "");
}
void test7(int i, String a) {
a = a + "0";
if (a.length() == k) {
System.out.println(""+a);
a = a.substring(0, a.length()-1);
a =a +"1";
System.out.println(a);
}else {
test7(i-1, a);
if (a.length() >1) {
a =a.substring(0, a.length()-1);
a =a+"1";
} else {
a = "1";
}
test7(i-1,a);
}
}
}
使用格雷码优化此 o/p 的任何方法。
【问题讨论】:
-
您希望优化什么?
-
第一个使用格雷码使得o/p为(00,01,10,11)...希望这很清楚
-
你不只是打印来自
0 to 2^k-1的二进制表示吗? -
订单 (00,01,10,11) 不是格雷码。对于格雷码,连续的元素必须只改变一位;您的第二个和第三个元素(01 和 10)有两位不同。正确的格雷码是 (00,01,11,10) 或 (00,10,11,01)。那么你想要格雷码顺序还是数字顺序? (或者别的什么?)
-
@P0W 是的...(stackoverflow 的填充)
标签: java recursion tail-recursion