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:
And to test this, you can call it in either of the following ways:
Or loop through all the possible combinations of grey codes up to the ith-bit:
Hope that proves helpful to folks!