SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
5.recursion
Exercise:
Programming Excercises
Question:21 | ISBN:978013274719 | Edition: 6

Question

(Binary to decimal) Write a recursive function that parses a binary number as a string into a decimal integer. The function header is as follows:
def binaryToDecimal(binaryString):
Write a test program that prompts the user to enter a binary string and displays its decimal equivalent.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Binary to decimal Program code:

#Recursive function to convert a binary number to decimal.
def binaryToDecimal(binaryString):
    # Base case: If the binary string is empty, return 0.
    if binaryString == '':
        return 0

    # Recursive case: Convert the binary number
    #excluding the last digit to decimal,
    # multiply it by 2, and add the value of the last digit.
    return binaryToDecimal(binaryString[:-1]) * 2 + int(binaryString[-1])


# Prompt the user for input
binary = input("Enter a binary number: ")

# Convert the binary number to decimal
decimal = binaryToDecimal(binary)

# Display the result
print(f"The decimal equivalent of {binary} is: {decimal}")

Executed Output:

Enter a binary number: 1101
The decimal equivalent of 1101 is: 13

 

0 0

Discussions

Post the discussion to improve the above solution.