[Java] Converting between Decimal and Binary with Recursion

I am trying to write a program that will convert a binary number into its equivalent decimal number using recursion. Recursion has always been a confusing topic in programming. I write a simple code to implement convert from decimal to binary and from binary to decimal.

Here’s my code:

```public class ConvertDecimaltoBinary {
static String strBinary;
private static String toBinary(int num) {
if (num < 2) {
strBinary = "" + num;
return strBinary;
} else {
toBinary(num / 2);
strBinary += "" + num % 2;
}
return strBinary;
}

private static long toDecimal(int[] bin) {
long decValue = 0L;
for (int i = 0; i < bin.length; i++) {
decValue <<= 1; // Shift content of decValue 1 position to the left
decValue += bin[i]; // add the 0 or 1
}
return decValue;
}

public static void main(String[] args) {
System.out.println("Binary= " + toBinary(100));
int bin[] = {1, 1, 0, 0, 1, 0, 0, 1};
System.out.println("Decimal= " + toDecimal(bin));
}
}
```

This recursive method uses an assigned integer for testing purposes, variable num, and will get the remainder of num divided by 2 using the modulo(%) operator. The remainder is assigned to variable strBinary, which will then be sent to be output and be displayed to the user.

Recursion process begins as the method calls on itself to do the computation again, a stopping condition is written with the if loop to check whether the number is no longer divisible by 2, and if the condition is true, the method will stop.

(Visited 24 times, 1 visits today)