简体   繁体   中英

Convert Decimal to Binary using Recursion Java

I am trying to simply convert to Binary with recursion. I am having problems with the return statement. This compiles but give an overflow error when run. I don't know what to return (or if my statement is wrong) to prevent this error.

Thanks!

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

   return convertToBinary((number));
}

Your problem was calling convertToBinary on both number/2 and number%2 I believe. This code works fine for me and isn't that different from what you had:

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 + " ");
    }
}

}

Well, the problem seems to be that you're not actually doing anything in your recursive method.

In its most basic form your recursive method should contain:

  1. One or more escape conditions.
  2. Recursive calls to itself.

(This is an oversimplified view, but it will do for now.)

The problem is that you're missing some escape conditions to handle the case of the parameter being a single bit long, that is when you can't subdivide it any more.

The other problem with your code is that you're not doing anything with the result of the recursive calls. You should store and concatenate them.

I suggest you start again: write a method that converts a single bit first (this will be non-recursive), then add the recursion to it. (A general advice: don't be afraid to throw away code and start again from scratch.)

Assuming this is homework I'll point out the main error..

return convertToBinary((number));

The return should return a value, not call a function. This will just adding a recursive state stacks which leads to your overflow. Try saving the values from your previous calls into a variable and returning that.

Once number reaches zero, the method will simply call itself over and over again. The final return needs to return something else - like a string. Having said that, I don't think this approach is terribly optimal.

Try below -:

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;
}

This works but you have to print it from end

static void printBinary(int x){
     if(x==0)System.out.printf("%3d", x);
      else{
           System.out.printf("%3d",x%2);
           printBinary(x/2);
      }
}

Following will work recursively. If number is negative it will add "-" as prefix to 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);
    }
}
class Example{
    public static String binary(int num){
        String b = " "; // create empty string to concat the binary values
        if (num == 0) {
            return "0"; // return 0 for decimel 0
        } else if(num == 1) {
            return "1"; // return 1 for decimel 1
        } else {
            return b + binary(num/2)+(num%2);
        }
    }
    
    public static void main(String args[]){
        System.out.println(binary(128));    //print 10000000
        System.out.println(binary(64));     //print 1000000
        System.out.println(binary(1));      //print 1
        System.out.println(binary(0));      //print 0
    }
}

I tried to create a generic sub-routine which takes any Decimal integer & convert it to required BASE.

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

Caution:- It will not work for negative numbers.

Just add the binary conversion of (number/2*10) to the remainder of the number:

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

    if (dec==1 || dec==0)
        return dec;
    else
        return remainder + (binary(dec/2)*10);
}
public class DecImalToBinary {
    public static String decimalToBinary(int num){
        StringBuilder sb= new StringBuilder();
        if (num <2){
            return ""+ num;
        }
        else{
            return (sb.append(num%2)) + decimalToBinary((num/2));           
        }
    }

    public static void main(String[] args){
        System.out.println(decimalToBinary(8));
    }
}
public String convertirABinario(int n){
    String b = "";
    if (n == 0 || n == 1){
      b = "" + n;
    }
    else{
      b = b + convertirABinario(n/2) + n%2;
    }
    return b;
}

Here is my solution:

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

have fun

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM