从一个递归函数返回多个值 [英] Returning multiple values from a recursive function

查看:138
本文介绍了从一个递归函数返回多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的问题,我必须的十进制数转换为二进制,然后存储该位在一个链表,其中头节点是最显著位和最后一个节点是最显著位。解决问题本身实际上是容易,因为你只需要继续服用2模递归,并在列表中添加的结果,直到十进制数变为0。

I have this problem where I have to convert a decimal number to binary and then store the bits in a linked list where the head node is the most significant bit and the last node is the least significant bit. Solving the problem itself is actually easy as you only need to keep taking the modulo of 2 recursively and add the result in the list until the decimal number becomes 0.

在哪里我坚持的是,我必须写等功能,它返回一对数,(无论是一个数组或列表)的最显著位,最后显著位。
即:在该函数直接输入14将二进制返回(1,0),自14是1110。

Where I'm stuck is that I have to write the function such that it returns a pair of number, (whether an array or a list) of the most significant bit and the last significant bit. i.e: Inputting 14 in the function would return (1, 0), since 14 is 1110 in binary.

我确实有机会获得MSB和LSB容易(getFirst(),getLast())。

I do have access to the MSB and LSB easily(getFirst(), getLast()).

该功能只能取一个参数,它是十进制数。

The function can only take one argument which is the decimal number.

目前我有这个当前code:

Currently I have this current code:

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的值。一个巡航能力的返回值意味着我不能自称EN codeBIN()。

The problem is I can't figure out how return the 2 values. Haveing a return value means I can't call encodeBin() by itself.

此外,我应该在哪里创建列表?如果我把类似列表<整数GT; =新的LinkedList<整数GT;()在函数的开始,那么每一个函数调用自身的时候,它会创建一个新的列表,并增加了位在新的列表不是原来的权利(?从当函数被调用首次创建的列表)

Moreover, where should I create the list? If I put something like List<Integer> = new LinkedList<Integer>() at the very beginning of the function, then each time the function calls itself, it creates a new list and adds the bits in THAT new list not the original right?(The list created from when the function is called the first time)

任何人知道如何解决这个问题?

Anybody knows how to solve this?

推荐答案

我建议声明两种方法:

(1)公共静态INT [] EN codeBIN(INT N)

(2)私有静态无效连接codeBIN(链表,INT N)

(1) public static int[] encodeBin(int n) and (2) private static void encodeBin(LinkedList, int n)

公共方法不过就是创建一个空的列表,然后调用私有版本同时传递空表和一部开拓创新的输入n作为参数

The public method merely creates an empty list and then calls the private version passing both the empty list and the orignal input n as the parameters

是这样的:

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
}

这篇关于从一个递归函数返回多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆