在java中将十进制转换为格雷码 [英] Convert decimal to gray code in java
本文介绍了在java中将十进制转换为格雷码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最近出现了一个问题:编写算法将十进制数转换为n位格雷码。
Had a question come up recently which was: write the algorithm to convert a decimal number to an n-bit gray code.
例如:
使用1位(最简单):
So for example: Using 1-bit (simplest):
0 -> 0
1 -> 1
使用2位
0 -> 00
1 -> 01
2 -> 11
3 -> 10
使用3位
0 -> 000
1 -> 001
2 -> 011
3 -> 010
4 -> 110
5 -> 111
6 -> 101
7 -> 100
推荐答案
写下以下内容并认为我会分享因为我没有看到很多Java实现出现在这里:
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));
或者循环遍历第i位的所有灰色代码组合:
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));
希望这对人们有帮助!
这篇关于在java中将十进制转换为格雷码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文