0

I want to convert the decimal number into a binary number using recursion in java. I tried a lot but unable to do it. Here is my code:

public class DecimalToBinary {


    public static void main(String[] args) {
        System.out.println(conversion(2));
    }

    public static int conversion(int n) {
         return reconversion(n);
    }

    public static int reconversion(int n) {
        if(n <= 0)
            return 0;
        else {

            return  (int) (n/2 + conversion(n/2));

        }
    }

}

1 Answer 1

2

Integer values are already in binary. The fact that they appear as digits 0 thru 9 when you print them is because they are converted to a string of decimal digits. So you need to return a String of binary digits like so.

   public static String conversion(int n) {
      String b = "";
      if (n > 1) {
         // continue shifting until n == 1
         b = conversion(n >> 1);
      }
      // now concatenate the return values based on the logical AND
      b += (n & 1);
      return b;

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

3 Comments

It shifts the value of n one bit to the right. So if n is 101 in binary, it will now call conversion with 10.
And what about the statement b+ = (n & 1); ?? I am unaware of ( n & 1). Kindly help me
That is a bit test for a value. It does a logical AND operation with n and a give mask. Since the mask is 1, it checks to see if the low order bit is set. It if is (1 & 1) returns a 1. If it isn't (0 & 1) returns a 0. Other bit operations are ~ and ^ and | which are complement, exclusive OR, and OR.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.