使用递归Java将十进制转换为二进制

使用递归Java将十进制转换为二进制,java,recursion,binary,decimal,Java,Recursion,Binary,Decimal,我试图简单地用递归转换成二进制。我对返回语句有问题。这会编译,但在运行时会出现溢出错误。我不知道返回什么,也不知道我的声明是否错误,以防止出现此错误 谢谢 public static String convertToBinary(int number) { if(number > 0) { convertToBinary(number / 2); convertToBinary((number % 2 )); } return conv

我试图简单地用递归转换成二进制。我对返回语句有问题。这会编译,但在运行时会出现溢出错误。我不知道返回什么,也不知道我的声明是否错误,以防止出现此错误

谢谢

public static String convertToBinary(int number)
{
  if(number > 0)
    {
      convertToBinary(number / 2);
      convertToBinary((number % 2 ));
     }

   return convertToBinary((number));
}

一旦这个数字达到零,这个方法就会一遍又一遍地调用自己。最后的返回需要返回其他内容,如字符串。话虽如此,我认为这种方法并不十分理想。

假设这是家庭作业,我会指出主要错误

return convertToBinary((number));

返回应该返回一个值,而不是调用函数。这只会添加一个递归状态堆栈,从而导致溢出。尝试将以前调用的值保存到一个变量中并返回该变量。

好吧,问题似乎是您在递归方法中没有实际执行任何操作

递归方法最基本的形式应包括:

一个或多个逃生条件。 对自身的递归调用。 这是一个过于简单的观点,但现在就可以了

问题是您缺少一些转义条件来处理参数只有一位长的情况,即无法再细分它

代码的另一个问题是没有对递归调用的结果进行任何处理。您应该存储并连接它们


我建议您重新开始:首先编写一个转换单个位的方法,这将是非递归的,然后向其中添加递归。一般建议:不要害怕扔掉代码,从头开始。

我相信您的问题是在数字/2和数字%2上调用convertToBinary。这段代码对我来说很好,与您的代码没有什么不同:

import java.util.Scanner;

public class DecToBin {

public static void main(String[] args) {

    int input;
    Scanner scan = new Scanner(System.in);

    System.out.print("Enter number to convert to binary: ");
    input = scan.nextInt();
    convert(input);

}

public static void convert(int num) {
    if (num>0) {
        convert(num/2);
        System.out.print(num%2 + " ");
    }
}

}

<>如果这不是家庭作业,可以考虑:


我试图创建一个通用子程序,它接受任何十进制整数并将其转换为所需的基数

private Integer convertToBaseN(int num,int n, int pow)
{
    Integer r = num%n;

    if(num < n)
        return new Double((Math.pow(10, pow-1))*r.doubleValue()).intValue();

    return convertToBaseN(num/n, n,pow+1)+ 
            new Double(Math.pow(10, pow-1)*r.doubleValue()).intValue();
}

    num :- Decimal No you want to convert.
    n:- Base to which you want to convert ( n =2 in your case).
    pow = 1 (fixed);


    Input=> convertToBaseN(503,5, 1); Output=> 4003
    Input=> convertToBaseN(7,2, 1); Output=> 111

注意:-它不适用于负数。

只需将数字/2*10的二进制转换添加到数字的其余部分:

int binary(int dec) {
    int remainder=dec%2;

    if (dec==1 || dec==0)
        return dec;
    else
        return remainder + (binary(dec/2)*10);
}

这行得通,但你必须从头开始打印

static void printBinary(int x){
     if(x==0)System.out.printf("%3d", x);
      else{
           System.out.printf("%3d",x%2);
           printBinary(x/2);
      }
}
以下是我的解决方案:

 public static String binaerRec(int number)
{
    if (number > 1)
    {
        return binaerRec(number / 2) + number % 2;
    } else
    {
        return 1 + "";
    }
}
玩得开心

试试下面-:

public static String dec2Bin(int num) {
    String result = ((num % 2 == 0) ? "0" : "1"); // expr

    if (abs(num) > 1) {
        result = dec2Bin(num / 2) + result;
    }

    return result;
}

下面的代码将递归地工作。若数字为负数,则会将-作为前缀添加到结果中

    void printBinary (int n) {
            if (n < 0) {         //base case
                System.out.print("-");
                printBinary(-n);
            } else if (n < 2) {    //base case
                System.out.print(n);
                return;
            } else {
                printBinary(n/2);   //recursive step
                int answer = n%2;   
                System.out.print(answer);
            }

        }

这是家庭作业吗?假设是,请给它贴上标签。你需要一个基本的箱子。这将永远运行,或者尝试运行,直到遇到溢出。@trutheality无论是否有基本大小写,最后一行都使用相同的参数调用自己,因此在下一级中不会发生任何更改。@Izkata。现在它还没到那里,你已经有二进制了。整数已经是二进制的。你的问题毫无意义。更糟糕的是,它总是一遍又一遍地调用自己,不管number的值是什么。虽然这段代码是递归的,但可能不是必需的,假设这确实是一个家庭作业。你能在回答问题的代码中提供更多信息吗?欢迎来到StackOverflow Julian。你能改进你的代码片段以提高可读性吗?此外,请提供一些描述性背景,说明您为什么认为这是问题的解决方案。有关帮助,请参阅关于StackOverflow.Integer.parseInt的说明。parseInt已执行十进制到二进制的转换。剩下的只是浪费时间。然而,值得赞扬的是,到目前为止,这是唯一一个认识到输入不能是整数的答案。这里没有十进制整数。
public static String dec2Bin(int num) {
    String result = ((num % 2 == 0) ? "0" : "1"); // expr

    if (abs(num) > 1) {
        result = dec2Bin(num / 2) + result;
    }

    return result;
}
    void printBinary (int n) {
            if (n < 0) {         //base case
                System.out.print("-");
                printBinary(-n);
            } else if (n < 2) {    //base case
                System.out.print(n);
                return;
            } else {
                printBinary(n/2);   //recursive step
                int answer = n%2;   
                System.out.print(answer);
            }

        }
class DecBin {
    static int convert(int i) {
        if (i > 0) {
            convert (i/2);
            System.out.println(i%2);
            return 0;
        } else {
            return 0;
        }
     }

    public static void main(String[]  args) {
        DecBin.convert(10);
    }
}