def binary_equivalent(number):
if number == 0:
return ""
return binary_equivalent(number // 2) + str(number % 2)
number = int(input("Enter an integer: "))
if number == 0:
print("The binary equivalent of 0 is 0.")
elif number > 0:
print(f"The binary equivalent of {number} is {binary_equivalent(number)}.")
else:
print(f"The binary equivalent of {number} is -{binary_equivalent(abs(number))}.")
#source code --> clcoding.com
Code Explanation:
1. Recursive Function: binary_equivalent(number)
This function computes the binary representation of a number using recursion.
def binary_equivalent(number):
if number == 0:
return ""
return binary_equivalent(number // 2) + str(number % 2)
Base Case:
if number == 0:
return ""
If the input number is 0, the function returns an empty string (""). This is the stopping condition for recursion. The binary representation is built as the recursion unwinds.
Recursive Case:
return binary_equivalent(number // 2) + str(number % 2)
For numbers greater than 0:
Integer Division (number // 2): Divides the number by 2, reducing it in each recursive call.
Modulo (number % 2): Finds the remainder when divided by 2, which represents the current binary digit (0 or 1).
The result is the binary representation of number // 2 concatenated with the binary digit of the current step.
2. Taking Input
number = int(input("Enter an integer: "))
Prompts the user to enter an integer.
Converts the input string into an integer using int().
3. Handling Special Cases
if number == 0:
print("The binary equivalent of 0 is 0.")
4. Positive Numbers
elif number > 0:
print(f"The binary equivalent of {number} is {binary_equivalent(number)}.")
If the input is positive, the program calls binary_equivalent(number) and prints the result.
5. Negative Numbers
else:
print(f"The binary equivalent of {number} is -{binary_equivalent(abs(number))}.")
If the input is negative:
The absolute value (abs(number)) is passed to the binary_equivalent function to compute the binary representation of the positive counterpart.
The program prepends a negative sign (-) to indicate the negative value.
0 Comments:
Post a Comment