写下以下内容,并认为我会分享它,因为在这里看不到许多Java实现:
static String getGreyCode(int myNum, int numOfBits) { if (numOfBits == 1) { return String.valueOf(myNum); } if (myNum >= Math.pow(2, (numOfBits - 1))) { return "1" + getGreyCode((int)(Math.pow(2, (numOfBits))) - myNum - 1, numOfBits - 1); } else { return "0" + getGreyCode(myNum, numOfBits - 1); }}static String getGreyCode(int myNum) { //Use the minimal bits required to show this number int numOfBits = (int)(Math.log(myNum) / Math.log(2)) + 1; return getGreyCode(myNum, numOfBits);}
为了对此进行测试,您可以通过以下两种方式之一进行调用:
System.out.println("Grey pre for " + 7 + " at n-bit: " + getGreyCode(7));System.out.println("Grey pre for " + 7 + " at 5-bit: " + getGreyCode(7, 5));
或遍历所有可能的格雷码组合,直到第i位:
for (int i = 1; i <= 4; i++) { for (int j = 0; j < Math.pow(2, i); j++) System.out.println("Grey pre for " + j + " at " + i + "-bit: " + getGreyCode(j, i));
希望对人们有帮助!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)