Program opened below. You can scroll through the algorithm, Java code and output.
Program 19
Recursive Binary to Decimal Conversion
Question
Design class Convert to accept a binary integer and calculate its decimal value recursively.
Algorithm
Step 1: Start and create an object of Convert.
Step 2: Read a nonnegative binary number into binum.
Step 3: Copy the number for validation.
Step 4: Inspect every decimal digit of the entered notation.
Step 5: Reject any digit other than zero or one.
Step 6: Call the recursive function with the binary number and place value one.
Step 7: Return zero if no digits remain.
Step 8: Extract the rightmost binary digit.
Step 9: Multiply that digit by the current power of two.
Step 10: Remove the rightmost digit using division by ten.
Step 11: Double the place value.
Step 12: Recursively convert the remaining binary digits.
Step 13: Add the current contribution and recursive result.
Step 14: Store the returned decimal number.
Step 15: Display the original binary number and calculated decimal value.
Step 16: Stop.
Java program
Javaimport java.util.*;
class Convert {
long binum;
long decinum;
void input() {
Scanner sc = new Scanner(System.in);
binum = sc.nextLong();
}
long BintoDeci(long d, long p) {
if (d == 0) {
return 0;
}
return (d % 10) * p + BintoDeci(d / 10, p * 2);
}
void display() {
long temp = binum;
if (temp < 0) {
System.out.println("Invalid binary number");
return;
}
while (temp > 0) {
if (temp % 10 > 1) {
System.out.println("Invalid binary number");
return;
}
temp /= 10;
}
decinum = BintoDeci(binum, 1);
System.out.println(binum + " = " + decinum);
}
public static void main(String[] args) {
Convert ob = new Convert();
ob.input();
ob.display();
}
}Sample output
Input: 1011
Output: 1011 = 11