0

So I have code that will convert a decimal number to binary. I use a recursive algorithm for it, however I cannot seem to get it to do what I want. Here is the code:

import java.util.*;

public class binaryAddition {

    public static int toBinary(int a){


        int bin = 0;
        int remainder = 0;
        if(a >= 1){
            toBinary(a/2);
            bin = (a%2);
        }

        return bin;


    }

    public static void main(String[] args){

        System.out.println(toBinary(3));
        System.out.print(toBinary(3));
    }
}

So I want to to return the binary solution so that I can save it as a variable in my main method. However, my current output would only give me that last digit of the binary number. I used the number 3 just as a test case and I get 1 as an output for both print and println methods. Why is that, and how can I fix it?

Many Thanks!

2

3 Answers 3

1

For a start, you might want to have toBinary return a String, not an int. Then you must use the result of it when you recurse. So you might write, inside your if,

bin = toBinary(a / 2) + (a % 2);

assuming, of course, that toBinary returns String.

If you don't do this, then you're just throwing away the result of your calculation.

Sign up to request clarification or add additional context in comments.

Comments

1

The code is discarding the results of the recursive calls.

Do something with the result of toBinary in the method.

Comments

0

Just Do it Like i have Done .

 public static void main(String[] args) 
{
    int n, count = 0, a;
    String x = "";
    Scanner s = new Scanner(System.in);
    System.out.print("Enter any decimal number:");
    n = s.nextInt();
    while(n > 0)
    {
        a = n % 2;
        if(a == 1)
        {
            count++;
        }
        x = x + "" + a;
        n = n / 2;
    }
    System.out.println("Binary number:"+x);
    System.out.println("No. of 1s:"+count);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.