Had a question come up recently which was: write the algorithm to convert a decimal number to an n-bit gray code.
So for example: Using 1-bit (simplest):
0 -> 0
1 -> 1
Using 2-bit
0 -> 00
1 -> 01
2 -> 11
3 -> 10
Using 3-bit
0 -> 000
1 -> 001
2 -> 011
3 -> 010
4 -> 110
5 -> 111
6 -> 101
7 -> 100
Wrote the following and figured I'd share it as I don't see many Java implementations showing up on here:
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);
}
And to test this, you can call it in either of the following ways:
System.out.println("Grey code for " + 7 + " at n-bit: " + getGreyCode(7));
System.out.println("Grey code for " + 7 + " at 5-bit: " + getGreyCode(7, 5));
Or loop through all the possible combinations of grey codes up to the ith-bit:
for (int i = 1; i <= 4; i++) {
for (int j = 0; j < Math.pow(2, i); j++)
System.out.println("Grey code for " + j + " at " + i + "-bit: " + getGreyCode(j, i));
Hope that proves helpful to folks!
来源:https://stackoverflow.com/questions/28841322/convert-decimal-to-gray-code-in-java