我有这个问题,我必须将十进制数转换为二进制,然后将位存储在链表中,其中头节点是最高有效位,最后一个节点是最低有效位。解决问题本身实际上很容易,因为你只需要递归取2的模数并将结果添加到列表中,直到十进制数变为0。
我被困住的地方是我必须编写函数,使得它返回最高有效位和最后有效位的一对数字(无论是数组还是列表)。即:在函数中输入14将返回(1,0),因为14是二进制的1110。
我可以轻松访问MSB和LSB(getFirst(),getLast())。
该函数只能使用一个十进制数参数。
目前我有这个当前的代码:
public static void encodeBin(int n) {
if(n == 0) return; //Base case
else {
if(n % 2 == 0)
theList.addFirst(0);
else
theList.addFirst(1);
encodeBin(n / 2);
}
// return?
}
问题是我无法弄清楚如何返回2个值。有一个返回值意味着我不能自己调用decodeBin()。
而且,我应该在哪里创建列表?如果我在函数的最开头添加类似List<Integer> = new LinkedList<Integer>()
的东西,那么每次函数调用自身时,它会创建一个新的列表,并在新的列表中添加不是原始权利的位?(从函数调用时创建的列表)第一次)
谁知道怎么解决这个问题?
您不能返回2个值。您将不得不返回包含2个值的对象。数组或新对象,取决于您的作业要求以及将使用此功能的位置。
对于链表创建,您需要的是递归帮助方法。您的公共方法将用于初始化对象,开始递归并返回结果。这允许您的实际递归函数具有多个参数。
public static SOME_TYPE encodeBin(int n) {
LinkedList result = new LinkedList();
encodeBin_helper(result,n);
// return the MSB and LSB
}
public static void encodeBin_helper(LinkedList theList, int n) {
if(n == 0) return; //Base case
else {
if(n % 2 == 0)
theList.addFirst(0);
else
theList.addFirst(1);
encodeBin_helper(theList, n/2);
}
}
您不能单独返回两个值。但是,您可以返回包含第一位和最后一位的数组,或者创建自己的类来保存此数据,并返回该类的实例。
关于列表,我看到两个选项:
static
类变量第一种方法如下所示:
public class MyClass {
private static List<Integer> theList = new LinkedList<Integer>();
// `encodeBin` method as you have it
}
第二种方法如下所示:
public static void encodeBin(int n, List<Integer> theList) {
if(n == 0) return; //Base case
else {
if(n % 2 == 0)
theList.addFirst(0);
else
theList.addFirst(1);
encodeBin(n / 2, theList);
}
}
然后你可以做一些事情
List<Integer> theList = new LinkedList<Integer>();
encodeBin(14, theList);
和theList
将根据需要保留适当的位。
作为一个注释,您可能要考虑将此列为布尔值而不是整数,true
表示1
,false
表示0
。
我建议声明两种方法:
(1)public static int [] encodeBin(int n)和(2)private static void encodeBin(LinkedList,int n)
public方法只创建一个空列表,然后调用私有版本,将空列表和orignal输入n作为参数传递
这样的事情:
public static int[] encodeBin(int n) {
LinkedList<Integer> aList = new LinkedList<Integer>();
encodeBin(aList , n);
int MSB = aList.getFirst();
int LSB = aList.getLast();
return new int[] {MSB, LSB};
}
private static void encodeBin(LinkedList<Integer> list, n) {
//your recursive version here
}